Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

ios - 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
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) 
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...