SeekToTime in AVPlayer stops playing streaming audio, when forward

让人想犯罪 __ 提交于 2019-11-30 21:17:00
Losiowaty

This answer is heavily based on this one : https://stackoverflow.com/a/7195954/765298 . Any and all credit should go there as this is merely a translation to swift.

You are right to assume that when seeking far forward to a part that has not been buffered yet the player stops. The thing is it still buffers the data, but doesn't start automatically when it is ready. So, to rephrase the linked answer to swift :

To setup your observers :

player.currentItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil)
player.currentItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil)

Note, that in order to be able to observe values, the passed self needs to inherit from NSObject.

And to handle them :

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

    guard keyPath != nil else { // a safety precaution
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        return
    }

    switch keyPath! {
        case "playbackBufferEmpty" :
            if player.currentItem!.playbackBufferEmpty {
                print("no buffer")
                // do something here to inform the user that the file is buffering
            }

        case "playbackLikelyToKeepUp" :
            if player.currentItem!.playbackLikelyToKeepUp {
                self.player.play()
                // remove the buffering inidcator if you added it
            }
    }
}

You can also get information about avaiable time ranges from the currently playing AVPlayerItem (you can acces it via player.currentItem if you haven't created it yourself). This enables you to indicate to user which parts of the file are ready to go.

As always you can read some more in the docs : AVPlayerItem and AVPlayer

To read more about key-value observing (KVO) : here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!