本文介绍了AVPlayer在缓冲后停止播放视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我从互联网上加载视频(10-40MB大)时,我无法提供流畅的播放体验。
When I load a video from the internet (10-40MB large) I am unable to provide a smooth playing experience.
我的AVPlayer要么加载整个视频,然后播放,或播放1s,缓冲,然后停止播放。
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
}
}
}
推荐答案
自 iOS 10.x 以来,您可以进行一些缓冲设置,例如,您可以决定缓存视频所需的秒数:
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)
}
这篇关于AVPlayer在缓冲后停止播放视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!