繁体   English   中英

检查AVPlayer的播放状态,并将叠加视图添加到AVPlayerViewController

[英]Check play state of AVPlayer and add overlay view to AVPlayerViewController

我想检查AVPlayerViewController是否正在播放视频或其仍在缓冲中。我还想在此AVPlayerViewController中使用下一个和上一个按钮添加叠加视图。 使用以下代码,我的视频正在缓冲中,但显示正常播放。我想跟踪其播放,暂停还是缓冲阶段。

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

为了检查播放器的状态,您可以添加一个定期的时间观察者:

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

handlePlayerStatus内部,您检查状态:

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

暂无
暂无

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

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