使用AVAudioPlayer时OSStatus错误2003334207

问题描述 投票:9回答:5

当按下按钮时,我正在尝试播放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()
}

这是日志:

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

EXC_BREAKPOINT发生在audioPlayer.delegate = self

Stack Overflow上的其他线程无济于事。有任何想法吗?谢谢

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

ios swift avaudioplayer
5个回答
4
投票

看起来你试图打开一个零值的变量。您应该安全地展开变量以防止这种情况发生。

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
}

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

一些问题需要研究:

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

4
投票

你正在检查audioPlayer是否是nil但是你继续使用它,就好像它不是。你可能想要这样的东西:

if audioPlayer == nil {
    if let e = err {
        println(e.localizedDescription)
    }
} else {
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    audioPlayer.play()
}

并做一些事情来实际处理错误情况而不仅仅是打印错误。


2
投票

这可能是由于尝试加载不存在的文件引起的。如果这有助于某人将调用添加到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)")
    }

0
投票

在我的情况下,我遇到了同样的问题,我发现在开始录制之前我需要设置它

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)

希望它能帮助任何人


0
投票

我也遇到了这个问题,在检查了音频文件url之后,发现它存储在Cache目录中。所以音频播放器可能根据你的“url”找不到音频文件。

请确保,url路径位于Document目录下。

© www.soinside.com 2019 - 2024. All rights reserved.