我想检查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")
}
答案 0 :(得分:1)
为了检查播放器的状态,您可以添加定期时间观察器:
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
}
}