我有从url加载视频并将播放器放在avplayerview控制器中的avplayer,但我不想缓冲和下载视频,直到用户按下播放按钮。我该怎么做?

var player: AVPlayer = AVPlayer(URL: nsurl)
var newVideoChunk: AVPlayerViewController = AVPlayerViewController()
                                newVideoChunk.player = player

最佳答案

使用来自nsurl的avplayer的avplayerview控制器?
您需要设置视频资源,并使用基于nsurl的资源创建一个playeritem。然后,您需要向该playeritem添加一个观察者(立即):

self.playerItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: Constants.AVPlayerStatusObservationContext)

从键值观察器例程中,可以捕获上下文并调用外部函数:
   override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    //
    if context == Constants.AVPlayerStatusObservationContext {
        if (keyPath! == "status") {
            if (player!.status == AVPlayerStatus.ReadyToPlay) {
                print("ready")
                readyToPlay()

            } else if (player!.status == AVPlayerStatus.Failed) {
                // something went wrong. player.error should contain some information
            } else if (player!.status == AVPlayerStatus.Unknown) {
                print("unknown")
            }
        }
    }
}

如果只想在单击按钮时处理缓冲和下载,请确保只在按钮操作方法中添加观察者。这对于文件URL和联机URL同样有效。
请查看我的示例要点了解更多信息:
VideoPlayerViewController.swift

10-07 18:57