How can I check if my AVPlayer is buffering?

后端 未结 10 1067
后悔当初
后悔当初 2020-12-01 06:02

I want to detect if my AVPlayer is buffering for the current location, so that I can show a loader or something. But I can\'t seem to find anything in the documentation for

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 06:50

    Hmm, the accepted solution didn't work for me and the periodic observer solutions seem heavy handed.

    Here's my suggestion, observe timeControlerStatus on AVPlayer.

    // Add observer
    player.addObserver(self,
                       forKeyPath: #keyPath(AVPlayer.timeControlStatus),
                       options: [.new],
                       context: &playerItemContext)
    
    // At some point you'll need to remove yourself as an observer otherwise
    // your app will crash 
    self.player?.removeObserver(self, forKeyPath: #keyPath(AVPlayer.timeControlStatus))
    
    // handle keypath callback
    if keyPath == #keyPath(AVPlayer.timeControlStatus) {
        guard let player = self.player else { return }
        if let isPlaybackLikelyToKeepUp = player.currentItem?.isPlaybackLikelyToKeepUp,
            player.timeControlStatus != .playing && !isPlaybackLikelyToKeepUp {
            self.playerControls?.loadingStatusChanged(true)
        } else {
            self.playerControls?.loadingStatusChanged(false)
        }
    }
    

提交回复
热议问题