Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayer stops playing video after buffering

When I load a video from the internet (10-40MB large) I am unable to provide a smooth playing experience.

My AVPlayer either loads the whole video and then plays it, or plays 1s, buffers and then just stops playing.

I tried endless libraries, buffer-observer methods, and tutorials. Nothing seems to help.

    .
    .
    .

    self.makeLoaderVisible()

    let playerItem = AVPlayerItem(url: url)
    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)

    avPlayer?.replaceCurrentItem(with: playerItem)
    avPlayer?.automaticallyWaitsToMinimizeStalling = false
    avPlayer?.playImmediately(atRate: 0)
//  avPlayer?.play()

    }


override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if object is AVPlayerItem {
        switch keyPath! {
        case "playbackBufferEmpty":
            // Show loader
            makeLoaderVisible()

        case "playbackLikelyToKeepUp":
            // Hide loader
            hideLoader()

        case "playbackBufferFull":
            // Hide loader
            hideLoader()

        default:
            return
        }
    }
}
like image 607
thelearner Avatar asked May 27 '18 16:05

thelearner


People also ask

How do I stop AVPlayer from buffering?

But you can check the boolean playbackLikelyToKeepUp property of the AVPlayerItem to check if the buffer is loading. I not then pause playback on the AVPlayer. If you will call [self. player replaceCurrentItemWithPlayerItem:nil]; buffering stops.

What is AVPlayerItem?

An object that models the timing and presentation state of an asset during playback.


1 Answers

Since iOS 10.x, you can make some buffer settings, for example you can decide how many seconds you'll need to buffering your video:

    if #available(iOS 10.0, tvOS 10.0, OSX 10.12, *) {
        avPlayer?.automaticallyWaitsToMinimizeStalling = .playWhenBufferNotEmpty
        //preferredForwardBufferDuration -> default is 0, which means `AVPlayer` handle it independently, try more seconds like 5 or 10.
        playerItem.preferredForwardBufferDuration = TimeInterval(5) 
    }
like image 184
Alessandro Ornano Avatar answered Sep 20 '22 13:09

Alessandro Ornano