How can I check if my AVPlayer is buffering?

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

    #Updated in Swift 4 and worked fine

    As through i have gone with accepted answer but didn't work in swift 4 for me so after certain research i have found this thinks from apple doc. There are two way to determine AVPlayer states that are,

    1. addPeriodicTimeObserverForInterval:queue:usingBlock: and
    2. addBoundaryTimeObserverForTimes:queue:usingBlock:

    and using ways is like this

    var observer:Any?
    var avplayer : AVPlayer?
    
    func preriodicTimeObsever(){
    
            if let observer = self.observer{
                //removing time obse
                avplayer?.removeTimeObserver(observer)
                observer = nil
            }
    
            let intervel : CMTime = CMTimeMake(1, 10)
            observer = avplayer?.addPeriodicTimeObserver(forInterval: intervel, queue: DispatchQueue.main) { [weak self] time in
    
                guard let `self` = self else { return }
    
                let sliderValue : Float64 = CMTimeGetSeconds(time)
               //this is the slider value update if you are using UISlider.
    
                let playbackLikelyToKeepUp = self.avPlayer?.currentItem?.isPlaybackLikelyToKeepUp
                if playbackLikelyToKeepUp == false{
    
                   //Here start the activity indicator inorder to show buffering
                }else{
                    //stop the activity indicator 
                }
            }
        }
    

    And Don't forget to kill time observer to save from memory leak. method for killing instance, add this method according to your need but i have used it in viewWillDisappear method.

           if let observer = self.observer{
    
                self.avPlayer?.removeTimeObserver(observer)
                observer = nil
            }
    

提交回复
热议问题