如何对 AVPlayer 的播放和暂停操作执行一些操作?

How to perform some action on Play and Pause actions of AVPlayer?

我已经使用 AVPlayer 在我的 swift 应用程序上播放视频。我想在视频中间放置一个播放按钮(自定义按钮)。我知道如何在点击按钮时播放和暂停视频。

当视频是 played/paused 默认按钮时,我找不到如何 show/hide 自定义按钮?当视频 played/paused 时是否有任何监听器或触发的东西?

我还想在默认控件中隐藏 "Audio & Subtitles" 图标。

以下是监听播放器状态变化和 hide/show 按钮的方法:(假设您的播放器名为 player,按钮为 playButton

player.addObserver(self, forKeyPath: "rate", options: .New, context: nil) // somewhere after player init
...
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
  if keyPath == "rate" {
    playButton.enabled = player.rate == 1 
  } else {
    super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
  }
}

如果播放器的速率等于0,则表示视频未在播放。

播放器初始化,

self.player?.addObserver(self, forKeyPath: "rate", options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if self.player?.rate == 0 {
        print("Pause")
    }else {
        print("Play")
    }
}