简体   繁体   English

来自NSURL的AVPlayer的AVPlayerViewController

[英]AVPlayerViewController with AVPlayer from NSURL

I have AVPlayer that load video from url and put player inside AVPlayerViewController but I do not want to buffer and download video until user press play button. 我有AVPlayer从URL加载视频并将播放器放入AVPlayerViewController但我不想缓冲和下载视频,直到用户按下播放按钮。 How should I do it? 我该怎么办?

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

AVPlayerViewController with AVPlayer from NSURL? 来自NSURL的AVPlayer AVPlayerViewController?

You will need to setup the video asset and create a playerItem with that NSURL based asset. 您需要设置视频资源并使用基于NSURL的资产创建playerItem。 Then you will need to add an observer to that playerItem (immediately): 然后你需要向该playerItem添加一个观察者(立即):

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

From within the key value observer routine you can trap the context and call an external function: 在键值观察器例程中,您可以捕获上下文并调用外部函数:

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

If you only want to handle the buffering and download when the button is clicked then make sure you add the observer only within the button action method. 如果您只想在单击按钮时处理缓冲和下载,请确保仅在按钮操作方法中添加观察者。 This will work just as well with a file URL as an online URL. 这与将文件URL作为在线URL一样有效。

Please check my sample gist for more information: 请查看我的示例要点以获取更多信息:

VideoPlayerViewController.swift VideoPlayerViewController.swift

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM