Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift AVAudioPlayer在展开可选值时意外发现nil_Swift_Audio_Nullreferenceexception_Optional - Fatal编程技术网

Swift AVAudioPlayer在展开可选值时意外发现nil

Swift AVAudioPlayer在展开可选值时意外发现nil,swift,audio,nullreferenceexception,optional,Swift,Audio,Nullreferenceexception,Optional,我得到了可选的展开错误,但我看不出是什么导致了它。我检查了mp3文件的位置好几次,在调试模式下我跟踪了每一行,似乎它在声音中得到了正确的文件路径 这是我的密码 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDid

我得到了可选的展开错误,但我看不出是什么导致了它。我检查了mp3文件的位置好几次,在调试模式下我跟踪了每一行,似乎它在声音中得到了正确的文件路径

这是我的密码

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    @IBAction func Laughing(sender: UIButton) {

        // Set the sound file name & extension
       var laughSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Laughing", ofType: "mp3")!)

        // Play the sound
        audioPlayer = AVAudioPlayer(contentsOfURL: laughSound, error: nil)
        audioPlayer.prepareToPlay()
        audioPlayer.play()


    }

}
这行给了我一个错误

audioPlayer.prepareToPlay()

音频文件的确切位置应该是什么?我将其存储在支持文件中,并直接将其拖动到Xcode。或者还有什么会导致这个问题?我已用尽搜索结果。

为什么不使用NSBundle.mainBundle.URLForResourceWithExtension:获取音频url?请确保您的音频是mp3类型的音频,为什么不传入一个错误指针而不是零?阅读错误比让我们猜测问题所在要容易得多。