我想从添加到xcode的文件夹中播放一些歌曲。
我使用选项卡式应用程序,代码如下所示:
func playThis(thisOne:String)
{
do
{
let audioPath = Bundle.main.path(forResource: thisOne, ofType: ".mp3")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioPlayer.play()
}
catch
{
print ("ERROR")
}
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = songs[thisSong] //error index out of range
}
但是当我运行它时,歌曲不会首先出现
视图控制器,当我单击第二个视图控制器选项卡时,应用程序崩溃,原因是:
索引超出范围
第一视图控制器代码是这样的:
import UIKit
import AVFoundation
var audioPlayer = AVAudioPlayer()
var songs:[String] = []
var thisSong = 0
var audioStuffed = false
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = songs[indexPath.row]
return cell
}
以及将歌曲传递到详细信息视图控制器的方式:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
do
{
let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioPlayer.play()
thisSong = indexPath.row
audioStuffed = true
}
catch
{
print ("ERROR")
}
}
第二个视图控制器代码:
override func viewDidLoad()
{
super.viewDidLoad()
gettingSongNames()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//FUNCTION THAT GETS THE NAME OF THE SONGS
func gettingSongNames()
{
let folderURL = URL(fileURLWithPath:Bundle.main.resourcePath!)
do
{
let songPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
//loop through the found urls
for song in songPath
{
var mySong = song.absoluteString
if mySong.contains(".mp3")
{
let findString = mySong.components(separatedBy: "/")
mySong = findString[findString.count-1]
mySong = mySong.replacingOccurrences(of: "%20", with: " ")
mySong = mySong.replacingOccurrences(of: ".mp3", with: "")
songs.append(mySong)
}
}
myTableView.reloadData()
}
catch
{
print ("ERROR")
}
}
最佳答案
无法从提供的代码中获取足够的条件,但是如果要停止崩溃,请处理异常并处理代码的每种情况
示例:在访问值之前,请始终检查array.count> 0。
在您的情况下:if songs.count > 0 {label.text = songs[thisSong]}