简体   繁体   中英

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. How should I do it?

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

AVPlayerViewController with AVPlayer from NSURL?

You will need to setup the video asset and create a playerItem with that NSURL based asset. Then you will need to add an observer to that playerItem (immediately):

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.

Please check my sample gist for more information:

VideoPlayerViewController.swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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