简体   繁体   中英

Check play state of AVPlayer and add overlay view to AVPlayerViewController

i want to check if AVPlayerViewController is playing video or its still buffering.i also want to add overlay view in this AVPlayerViewController with next and previous button. with the following code my video is buffering but it shows normal playback.i want to track if its playing or its in pause or its in buffering stage.

    let playerAV = AVPlayerViewController()
    var player = AVPlayer()
    let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.d e/big_buck_bunny.mp4")
     player = AVPlayer(URL:videoURL!)
    playerAV.player = player
    playerAV.view.frame = self.movieView.frame
    self.addChildViewController(playerAV)

    self.movieView.addSubview(playerAV.view)
    playerAV.didMoveToParentViewController(self)

    playerAV.contentOverlayView?.addSubview(viewNext)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.notificationObserver(_:)), name:AVPlayerItemDidPlayToEndTimeNotification , object: player.currentItem)

    player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)
    _ = UIDevice.beginGeneratingDeviceOrientationNotifications
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.deviceOrientationDidChange(_:)) , name:
        UIDeviceOrientationDidChangeNotification, object: nil)


override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "rate" {
        if let rate = change?[NSKeyValueChangeNewKey] as? Float {
            if rate == 0.0 {
                print("playback stopped")
            }
            if rate == 1.0 {
                print("normal playback")
            }
            if rate == -1.0 {
                print("reverse playback")
            }
        }
    }
    print("you are here")
}

In order to check the state of the player you can add a periodic time observer:

player.addPeriodicTimeObserverForInterval(CMTime(value: 1, timescale: 3), queue: dispatch_get_main_queue()) { [weak self] time in
     self?.handlePlayerStatus(time)
}

Inside handlePlayerStatus you check for the state:

func handlePlayerStatus(time: CMTime) {
    if player.status == .ReadyToPlay {
         // buffering is finished, the player is ready to play
    }
}

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