AVPlayerViewController with AVPlayer from NSURL

I have an AVPlayer that loads a video from url and puts the player inside an AVPlayerViewController, but I don't want to buffer and load the video until the user clicks the play button. How should I do it?

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

      

+3


source to share


1 answer


AVPlayerViewController with AVPlayer from NSURL?

You will need to set up a video object and create a playerItem with this NSURL based resource. Then you will need to add an observer to this PlayerItem (right away):

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

      

As part of the procedure for viewing a key value, you can mask 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 want to handle buffering and loading on button click make sure you only add the observer to the button action method. This will work the same way as the file url as an online address.

For more information please check my example:

VideoPlayerViewController.swift

+2


source







All Articles