一尘不染

AVPlayer缓冲后停止播放视频

swift

当我从互联网上加载视频(10-40MB大)时,无法提供流畅的播放体验。

我的AVPlayer要么加载整个视频然后播放,要么播放1s,缓冲然后停止播放。

我尝试了无尽的库,缓冲区观察者方法和教程。似乎没有任何帮助。

    .
    .
    .

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

阅读 334

收藏
2020-07-07

共1个答案

一尘不染

iOS 10.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) 
    }
2020-07-07