首页 文章

Swift - 播放声音时我收到错误“致命错误:在解开Optional值时意外发现nil”

提问于
浏览
0

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

“致命错误:在打开可选值时意外发现nil”

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

3 回答

  • 0

    NSBundle pathForResource(name: String?, ofType ext: String?) -> String? 返回一个可选项,您将强制解包 . 您的路径错误或您的资源不存在 .

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

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

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

    即使你的函数安全地检查它的数据的有效性,这也是崩溃的原因是因为你强行打开你的枚举器对象,它在调用函数之前崩溃 . 您还需要安全地检查一个!

    或者,当我再次浏览你的代码时,声音对象永远不会被创建(可能在包中找不到或名称不正确),然后当你试图强行打开它时,它也可能崩溃 . 您的打印声明是否已打印过?

  • 0

    只要playSound函数完成,您在playSound函数中进行了delcared的audioPlayer常量就会被触发 .

    将audioPlayer声明为类级别的属性,然后播放声音 .

    以下是示例代码:

    class ViewController: UIViewController {
    
    var audioPlayer = AVAudioPlayer()
    
    ...........
    

    func playSound(soundName:String){

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

相关问题