swift - bgMusic - fatal error: unexpectedly found nil while unwrapping an Optional value

swift - bgMusic - fatal error: unexpectedly found nil while unwrapping an Optional value

我在我的应用程序中发现了一个错误,但只有当该应用程序在设备上运行时,如果该应用程序使用模拟器运行,才不会生成错误。

我已经定位到背景音乐脚本的错误,输出错误是fatal error: unexpectedly found nil while unwrapping an Optional value。我在这里看过类似的问题,但没有找到补救措施。

任何人都可以帮助修复我的代码吗?

    var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif")!
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil) //error here!!!
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()

如果您需要更多代码,请告诉我。

谢谢。

仔细检查设备上的以下内容是否为零:

NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif")

强制解包 NSURL 的失败初始化请求崩溃。您应该将值绑定为:

if let bgMusicURL = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif") {
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}

你的 bgMusic.aif 文件添加到你的目标了吗?

如果不是,可能在模拟器上可以正常播放,但在设备上就不行