使用AVAudioPlayer时OSStatus错误2003334207

use*_*220 10 avaudioplayer ios swift

当按下按钮时,我正在尝试播放MP3文件(当通过VLC/iTunes播放时起作用).这是我的代码:

     var audioPlayer: AVAudioPlayer!
     @IBAction func playEpisode(sender: AnyObject) {
    println("now playing")
    let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
    let data: CDEpisode = fetchedResultsController.objectAtIndexPath(indexPath!) as! CDEpisode
    var err: NSError?
    let url = NSURL(string: data.localPath)
    println("The url is \(url)")

    audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &err)
    if audioPlayer == nil {
        if let e = err {
            println(e.localizedDescription)
        }
    }
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    audioPlayer.play()
}
Run Code Online (Sandbox Code Playgroud)

这是日志:

now playing
The url is Optional(file:///var/mobile/Containers/Data/Application/4747A71E-A63F-4EFC-B2DF-8B361361080B/Documents/serial-s01-e12.mp3)
The operation couldn’t be completed. (OSStatus error 2003334207.)
fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

EXC_BREAKPOINT上发生audioPlayer.delegate = self.

StackoOverflow上的其他线程没有帮助.有任何想法吗?谢谢

编辑:我已经尝试将localURL传递给contentsOfURL(而不是CDEpisode对象),但它仍然失败.

chr*_*ram 6

看起来您试图解开一个具有 nil 值的变量。您应该安全地解开变量以防止这种情况发生。

if let data: CDEpisode = fetchedResultsController.objectAtIndexPath(indexPath!) as! CDEpisode
{
    var err: NSError?
    let url = NSURL(string: data.localPath)
    println("The url is \(url)")

    //rest of code
}
Run Code Online (Sandbox Code Playgroud)

您仍然需要弄清楚为什么它返回 nil,但这是一种更安全的解包变量并防止崩溃的方法,因为需要更多上下文来解决该问题。

一些需要研究的问题:

  • 您确定 fetchedResultsController 完全返回一个对象吗?
  • 你确定是CDEpisode?


Dim*_*urg 6

这可能是由于尝试加载不存在的文件造成的。如果这有助于某人添加呼叫url.checkResourceIsReachable()将记录更多描述性消息。

示例代码:

    do {
        let url = URL(fileURLWithPath: dbObject.path)
        let isReachable = try url.checkResourceIsReachable()
        // ... you can set breaking points after that line, and if you stopped at them it means file exist.
    } catch let e {
        print("couldnt load file \(e.localizedDescription)")
    }
Run Code Online (Sandbox Code Playgroud)


Tên*_*Tên 6

试试这个

var player: AVAudioPlayer = AVAudioPlayer()


@IBAction func playX(_ sender: Any) {
    let urlstring = "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
    let url = URL(string: urlstring)
    let data = try! Data(contentsOf: url!)
    player = try! AVAudioPlayer(data: data)
    player.prepareToPlay()
    player.volume = 1.0
    player.play()
}
Run Code Online (Sandbox Code Playgroud)