Swift - While playing sound I get error "fatal error: unexpectedly found nil while unwrapping an Optional value"

Swift - While playing sound I get error "fatal error: unexpectedly found nil while unwrapping an Optional value"

我正在使用 Xcode 7.0.1 Swift 2 iOS 9. 播放声音时出现此错误:

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

这是我的代码:

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")
    }
}

即使您的函数正在安全地检查其数据的有效性,它也会崩溃的原因是您强制解包您的枚举器对象,该对象在函数被调用之前崩溃。你也需要安全地检查那个!

或者,当我再次浏览您的代码时,声音对象从未被创建(可能未在包中找到或名称不正确),然后当您尝试强制解包时,它也可能崩溃。你打印过打印语句吗?

您在 playSound 函数中指定的 audioPlayer 常量会在 playSound 函数完成后立即解除分配。

在 class 级别将 audioPlayer 声明为 属性,它们会播放声音。

示例代码如下:

class ViewController: UIViewController {

var audioPlayer = AVAudioPlayer()

...........

func playSound(声音名称:字符串){

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

NSBundle pathForResource(name: String?, ofType ext: String?) -> String? returns 一个可选的,你正在强制展开。您的路径错误或您的资源不存在。

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

为了安全起见,当您不确定可选值是否有价值时,您应该始终检查可选值

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