【发布时间】:2015-05-15 15:16:13
【问题描述】:
我正在尝试下载和播放远程 mp3。
基本上:
- 用户点击了 mp3,
- 从后台开始下载
- 然后在可能的情况下开始播放。
一切正常 - 下载由 AFHTTPRequestOperation 执行,它直接将 mp3 下载到文件中,我每隔 1000 字节 左右获得一次进度更新。
问题是我不知道何时开始播放
AVAudioPlayer.
AVAudioPlayer 可以播放未完成的 mp3,但如果没有足够的数据,它会触发 fatalError (EXC_BREAKPOINT) 并且我的应用程序崩溃
- 它甚至不返回错误。
我提前知道 mp3 的持续时间,我可以从中确定大约。下载了多少秒的播放时间 - (sizeDownloaded/totalSize)*duration,但这很愚蠢,有时它会失败(我猜是因为文件开头有 ID3 标签,它可以包含巨大的图像,我的近似是没有意义的)。
我当前的代码:
op.setDownloadProgressBlock({bytesRead, totalBytesRead, totalBytesExpectedToRead in
let approxBytesForOneSecond = totalBytesExpectedToRead/Int64(downloadableItem.length)
let approxSecondsDownloaded = totalBytesRead/approxBytesForOneSecond
if approxSecondsDownloaded > kMinimumSecondsDownloadedForPlay { //min. secs = 5
var error: NSError?
self.player = AVAudioPlayer(contentsOfURL: url, error: &error) // This is the line where I sometimes get EXC_Breakpoint. The reason for this is that the mp3 is not playable yet ...
if (error != nil) {
// Error initializing item - never called
} else {
// Item initialized OK -> Play
}
}
})
那么,是否有一些可靠的方法可以确定文件是否可播放?
我知道提高播放开始的限制会有所帮助,但这似乎并不正确。 “等到下载完成”不是答案... :)
非常感谢!
【问题讨论】:
标签: ios objective-c swift mp3 avaudioplayer