AVPlayer 缓冲后停止播放视频
AVPlayer stops playing video after buffering
当我从互联网加载视频(10-40MB 大)时,我无法提供流畅的播放体验。
我的 AVPlayer 要么加载整个视频然后播放,要么播放 1 秒,缓冲然后停止播放。
我尝试了无穷无尽的库、缓冲区观察器方法和教程。似乎没有任何帮助。
.
.
.
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
}
}
}
由于iOS10.x,您可以进行一些缓冲设置,例如,您可以决定缓冲视频所需的秒数:
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)
}
当我从互联网加载视频(10-40MB 大)时,我无法提供流畅的播放体验。
我的 AVPlayer 要么加载整个视频然后播放,要么播放 1 秒,缓冲然后停止播放。
我尝试了无穷无尽的库、缓冲区观察器方法和教程。似乎没有任何帮助。
.
.
.
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
}
}
}
由于iOS10.x,您可以进行一些缓冲设置,例如,您可以决定缓冲视频所需的秒数:
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)
}