Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if my AVPlayer is buffering?

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 AVPlayer.

like image 598
vrwim Avatar asked Aug 10 '16 07:08

vrwim


2 Answers

You can observe the values of your player.currentItem:

playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil) playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil) playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .New, context: nil) 

then

override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {     if object is AVPlayerItem {         switch keyPath {             case "playbackBufferEmpty":                // Show loader              case "playbackLikelyToKeepUp":                 // Hide loader              case "playbackBufferFull":                 // Hide loader         }     } } 
like image 185
Marco Santarossa Avatar answered Oct 06 '22 10:10

Marco Santarossa


The accepted answer didn't work for me, I used the code below to show the loader efficiently.

Swift 3

//properties  var observer:Any! var player:AVPlayer!   self.observer = self.player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 600), queue: DispatchQueue.main) {     [weak self] time in      if self?.player.currentItem?.status == AVPlayerItemStatus.readyToPlay {          if let isPlaybackLikelyToKeepUp = self?.player.currentItem?.isPlaybackLikelyToKeepUp {             //do what ever you want with isPlaybackLikelyToKeepUp value, for example, show or hide a activity indicator.         }     } } 
like image 33
aytek Avatar answered Oct 06 '22 10:10

aytek