当我尝试使用swift播放音频文件时应用程序崩溃

时间:2015-10-08 01:30:57

标签: ios swift avaudioplayer

func playCorrectSound() {
    let soundURL: NSURL = NSBundle.mainBundle().URLForResource("correct", withExtension: "m4a")!
    correctSound = try! AVAudioPlayer(contentsOfURL: soundURL)
    correctSound.play()


}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    if correctIncorrectField.text == answerField.text && correctIncorrectField.text != "" && answerField.text != "" {
        pointsNum = pointsNum + 10
        points.text = "\(pointsNum)"
        textField.text = ""
        textField.hidden = true
        correctIncorrect.hidden = false
        correctIncorrect.textColor = UIColor.greenColor()
        correctIncorrect.text = "Correct!"
        pauseAndDoStuff()
        playCorrectSound()

    }
    if correctIncorrectField.text != answerField.text && correctIncorrectField.text != "" && answerField.text != "" {
        pointsNum = pointsNum - 5
        points.text = "\(pointsNum)"
        textField.text = ""
        textField.hidden = true
        correctIncorrect.hidden = false
        correctIncorrect.textColor = UIColor.redColor()
        correctIncorrect.text = "Incorrect!"
        pauseAndDoStuff()
    }
    textField.resignFirstResponder()
    return true
}

由于某种原因,它崩溃了

let soundURL: NSURL = NSBundle.mainBundle().URLForResource("correct", withExtension: "m4a")!

行和它唯一的说法:

  

致命错误:在解包可选值时意外发现nil。

1 个答案:

答案 0 :(得分:3)

确保项目中存在correct.m4a文件

并且它已包含在Copy Bundle Resources

中的Target -> Build Phases

enter image description here