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

标签 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")!

行及其唯一的说法:

fatal error: unexpectedly found nil while unwrapping an Optional value.

最佳答案

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

并且它包含在 Target -> Build PhasesCopy Bundle Resources

enter image description here

关于ios - 当我尝试使用 swift 播放音频文件时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005147/

相关文章:

ios - 如何快速接收服务器的响应?

ios - 如何在 iOS 7(越狱)中获取 SpringBoard 的任务端口?

ios - 如何将数据从 UIViewController 发送到 UITabBarControllers swift ios 中的第一个选项卡

ios - 我在 ios 应用程序中实现了谷歌登录。现在,我如何验证用户是否已登录,如果没有 - 使用 Swift 将他返回到登录页面?

ios - 键盘有时会显示在 iOS 的文本字段选择器 View 中

ios - 文本字段的最大字符限制

ios - 如何在 iOS 中播放循环视频?

iphone - 获取以 kb 为单位的音频文件大小

ios - 游戏运行一段时间后 AVAudioPlayer 返回 nil

ios - 如何在单击下一个按钮时播放下一首歌曲