我一直在使用 AVPlayer 从远程源流式传输音乐。我得到 URL,使用一个来创建 AVPlayerItem,然后我将其与我的 AVPlayer 实例相关联。我向与播放器关联的项目添加了一个观察者,以观察项目何时结束播放 ( AVPlayerItemDidPlayToEndTimeNotification
)。当观察者在项目结束时通知我时,我会创建一个新的 AVPlayerItem 并重新开始。这在 iOS 9.2 的前台和后台运行良好。
问题:由于我已更新到 iOS 9.3,这在后台无法运行。以下是相关代码:
var portionToBurffer = Double()
var player = AVPlayer()
func prepareAudioPlayer(songNSURL: NSURL, portionOfSongToBuffer: Double){
self.portionToBuffer = portionOfSongToBuffer
//create AVPlayerItem
let createdItem = AVPlayerItem(URL: songNSURL)
//Associate createdItem with AVPlayer
player = AVPlayer(playerItem: createdItem)
//Add item end observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)
//Use KVO to see how much is loaded
player.currentItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: .New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "loadedTimeRanges" {
if let loadedRangeAsNSValueArray = player.currentItem?.loadedTimeRanges {
let loadedRangeAsCMTimeRange = loadedRangeAsNSValueArray[0].CMTimeRangeValue
let endPointLoaded = CMTimeRangeGetEnd(loadedRangeAsCMTimeRange)
let secondsLoaded = CMTimeGetSeconds(endPointLoaded)
print("the endPointLoaded is \(secondsLoaded) and the duration is \(CMTimeGetSeconds((player.currentItem?.duration)!))")
if secondsLoaded >= portionToBuffer {
player.currentItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
player.play()
}
}
}
}
func playerItemDidReachEnd(notification: NSNotification){
recievedItemEndNotification()
}
func recievedItemEndNotification() {
//register background task
bgTasker.registerBackgroundTask()
if session.playlistSongIndex == session.playlistSongTitles.count-1 {
session.playlistSongIndex = 0
} else {
session.playlistSongIndex += 1
}
prepareAudioPlayer(songURL: session.songURLs[session.playlistSongIndex], portionOfSongToBuffer: 30.00)
}
我设置了断点以查看player.play()
在后台调用 IS。当我打印player.rate
它读取0.0
。我检查了playbackLikelyToKeepUp
AVPlayerItem 的属性,它是true
. 我还确认新 URL 已成功用于创建新的 AVPlayerItem 并在应用程序处于后台时与 AVPlayer 关联。我已经打开了音频和播放后台功能,我什至打开了一个有限长度的后台任务(在上面的代码中bgTasker.registerBackgroundTask
)。不知道发生了什么。
我找到了这个,但我不确定它是否有帮助。任何建议都会很棒,谢谢