尝试在 Swift 中播放音频时出现致命错误

Fatal error when trying to play audio in Swift

正在尝试播放音频但一直收到 fatal error:

unexpectedly found nil while unwrapping an Optional value

这是我的代码:

import UIKit
import AVFoundation

class PlaySoundsViewController: UIViewController {

    var audioPlayer : AVAudioPlayer!

    override func viewDidLoad() {

        super.viewDidLoad()
        // Do any additional setup after loading the view.
        if var filePath = NSBundle.mainBundle().pathForResource("movie", ofType: "mp3"){
            var filePathURL = NSURL.fileURLWithPath(filePath)
            var audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL!, error: nil)

        }else{
            println("the filePath is empty")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func playSlowAudio(sender: UIButton) {
        //play sloooowly
        audioPlayer.play()
    }
}

看起来 var filePathURL = NSURL.fileURLWithPath(filePath) 正在返回 nil,包裹在一个 Optional 中。然后在下一行 filePathURL! 强制 Optional 展开,导致 nil 并给出您看到的错误。

您应该检查以确保 filePath 对于您尝试加载的文件是正确的。确保文件在您的包中并且您输入的文件名正确。在那里设置断点和调试可能会有所帮助。

此外,为了更安全,您可能需要更改 if 语句,使 NSURL.fileURLWithPath(filePath) 成为 if:

的一部分
if let filePath = NSBundle.mainBundle().pathForResource("movie", ofType: "mp3"),
   let filePathURL = NSURL.fileURLWithPath(filePath) {
    var audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL, error: nil)

}else{
    println("the filePath is empty OR the file did not load")
}

另请注意:我使用 let 而不是 var 作为 if 语句中的变量,因此它们是常量。最好尽可能使用 let