How can I check if my AVPlayer is buffering?

后端 未结 10 1074
后悔当初
后悔当初 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

    Here is a simple method, that works with Swift 5.

    This will add the loadingIndicator when your player is stalled

    NotificationCenter.default.addObserver(self, selector:
    #selector(playerStalled(_:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: self.player?.currentItem)
    
    @objc func playerStalled(_ notification: Notification){
        self.loadingIndicator.isHidden = false
        self.playPauseButton.isHidden = true
    }
    

    This will show loader Indicator when buffer is empty:

    if let isPlayBackBufferEmpty = self.player?.currentItem?.isPlaybackBufferEmpty{
        if isPlayBackBufferEmpty{
            self.loadingIndicator.isHidden = false
            self.playPauseButton.isHidden = true
        }
    }
    

    This will hide the loader when player is ready to play:

    if self.playerItem?.status == AVPlayerItem.Status.readyToPlay{
        if let isPlaybackLikelyToKeepUp = self.player?.currentItem?.isPlaybackLikelyToKeepUp {
            if isPlaybackLikelyToKeepUp{
                self.loadingIndicator.isHidden = true
                self.playPauseButton.isHidden = false
            }
        }
    }
    

提交回复
热议问题