3

我有从 url 加载视频并将播放器放入 AVPlayerViewController 的 AVPlayer,但我不想缓冲和下载视频,直到用户按下播放按钮。我该怎么做?

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

1 回答 1

2

AVPlayerViewController 与来自 NSURL 的 AVPlayer?

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

于 2015-07-09T20:28:06.190 回答