gpt4 book ai didi

ios - Swift - 播放声音时出现错误 "fatal error: unexpectedly found nil while unwrapping an Optional value"

转载 作者:行者123 更新时间:2023-11-30 13:54:54 25 4
gpt4 key购买 nike

我使用的是 Xcode 7.0.1 Swift 2 iOS 9。播放声音时出现此错误:

"fatal error: unexpectedly found nil while unwrapping an Optional value"

Error Screenshot

这是我的代码:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
playSound(enumerator![indexPath.item] )
}

func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}

最佳答案

NSBundle pathForResource(name: String?, ofType ext: String?) -> String? 返回一个可选值,并且您正在强制展开。要么你的路径错误,要么你的资源不存在。

并且查看图像声音名称的扩展名是.m4a。如果您想自己提供扩展,可以跳过 ofType 并传递 nil 或将扩展与资源名称分开并发送两个参数。

为了安全起见,当您不确定选项是否有值(value)时,应该始终检查它是否有值(value)

let pathComponents = soundName.componentsSeparatedByString(".")
if let filePath = NSBundle.mainBundle().pathForResource(pathComponents[0], ofType: pathComponents[1]) {
let coinSound = NSURL(fileURLWithPath: filePath)
}

关于ios - Swift - 播放声音时出现错误 "fatal error: unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com