AVPlayerViewController 与来自 NSURL 的 AVPlayer

AVPlayerViewController with AVPlayer from NSURL

我有 AVPlayer 从 url 加载视频并将播放器放在 AVPlayerViewController 中,但我不想在用户按下播放按钮之前缓冲和下载视频。我应该怎么做?

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

AVPlayerViewController 与来自 NS 的 AVPlayerURL?

您将需要设置视频资产并使用该基于 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