尝试在Swift中播放音频时出现致命错误 [英] Fatal error when trying to play audio in Swift

查看:385
本文介绍了尝试在Swift中播放音频时出现致命错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试播放音频,但继续接收fatal error:

Trying to play audio but keep receiving fatal error:

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

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并给出您看到的错误.

It looks like var filePathURL = NSURL.fileURLWithPath(filePath) is returning nil, wrapped in an Optional. Then on the next line filePathURL! forces the Optional to unwrap, resulting in nil and giving the error you see.

您应该检查以确保filePath对于您要加载的文件是正确的.确保文件在您的捆绑包中,并且您正确键入了文件名.在此处设置断点并进行调试可能会有所帮助.

You should check to make sure the filePath is correct for the file you are trying to load. Make sure the file is in your bundle and that you typed the file name correctly. Setting a breakpoint there and debugging would probably be helpful.

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

Also, to be safer, you may want to change the if statement so NSURL.fileURLWithPath(filePath) is part of the 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")
}

另外请注意:对于if语句中的变量,我使用了let而不是var,因此它们是常量.最好在可能的情况下使用let.

Also note: I used let instead of var for the variables in the if statement so they are constants. It is good practice to use let when you can.

这篇关于尝试在Swift中播放音频时出现致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆