当按下按钮时,我正在尝试播放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对象),但它仍然失败。
看起来你试图打开一个零值的变量。您应该安全地展开变量以防止这种情况发生。
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的原因,但这是一种更安全的解包变量并防止崩溃的方法,因为需要更多的上下文来解决该问题。
一些问题需要研究:
你正在检查audioPlayer
是否是nil
但是你继续使用它,就好像它不是。你可能想要这样的东西:
if audioPlayer == nil {
if let e = err {
println(e.localizedDescription)
}
} else {
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
}
并做一些事情来实际处理错误情况而不仅仅是打印错误。
这可能是由于尝试加载不存在的文件引起的。如果这有助于某人将调用添加到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)")
}
在我的情况下,我遇到了同样的问题,我发现在开始录制之前我需要设置它
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
希望它能帮助任何人
我也遇到了这个问题,在检查了音频文件url之后,发现它存储在Cache目录中。所以音频播放器可能根据你的“url”找不到音频文件。
请确保,url路径位于Document目录下。