如何在点击播放时添加回叫或获取通知?

时间:2015-11-01 18:47:39

标签: ios swift avplayer

我已使用以下代码在视图中添加了视频:

let url = NSBundle.mainBundle().URLForResource("etude", withExtension:"mp4")
player = AVPlayer(URL: url!)  
let playerViewController = AVPlayerViewController()
playerViewController.player = player
playerViewController.view.frame = CGRect(x: xPos, y: yPos, width: videoWidth, height: videoHeight)
self.view.addSubview(playerViewController.view)
self.addChildViewController(playerViewController)

当用户点击播放器上的播放按钮时,我还会触发其他一些事件。是否有一种很好的方法可以在发生这种情况时设置回调,或者添加一个观察者来检测它?

1 个答案:

答案 0 :(得分:0)

是的,您可以为playerViewController.player.rate注册Key-Value-Observing。

看起来像

self.player.addObserver(observer:self,keyPath:"rate",options:0,context:nil)

然后实施

func observeValueForKeyPath(_ keyPath: String?,
                   ofObject object: AnyObject?,
                     change change: [String : AnyObject]?,
                    context context: UnsafeMutablePointer<Void>)
{
  if(self.player.rate==1){
     print("playing")
  }else if(self.player.rate == 0){
     print("stopped")
  }
}