如何使用AVPlayerViewController检测播放控件的显示上的切换?

时间:2019-03-12 15:34:27

标签: ios swift avplayer avplayerviewcontroller

我想知道是否可以检测播放控件何时出现在AVPlayerViewController视图中。 我试图在播放器上添加一个UI元素,该元素必须遵循播放控件的显示。仅在显示控件时出现,否则消失

我似乎找不到任何可以在AVPlayerViewController上观察到的值来实现这一目标,也找不到任何回调或委托方法。

我的项目在Swift中。

1 个答案:

答案 0 :(得分:0)

观察和响应播放更改的一种简单方法是使用键值观察(KVO)。在您的情况下,请观察AVPlayer的timeControlStatusrate属性。

例如:

{
  // 1. Setup AVPlayerViewController instance (playerViewController)

  // 2. Setup AVPlayer instance & assign it to playerViewController

  // 3. Register self as an observer of the player's `timeControlStatus` property

  // 3.1. Objectice-C
  [player addObserver:self
           forKeyPath:@"timeControlStatus"
              options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew // NSKeyValueObservingOptionOld is optional here
              context:NULL];

  // 3.2. Swift
  player.addObserver(self,
                     forKeyPath: #keyPath(AVPlayer.timeControlStatus),
                     options: [.old, .new], // .old is optional here
                     context: NULL)
}

要通知状态更改,请实施-observeValueForKeyPath:ofObject:change:context:方法。每当timeControlStatus值更改时,都会调用此方法。

// Objective-C
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary <NSKeyValueChangeKey, id> *)change
                       context:(void *)context
{
  if ([keyPath isEqualToString:@"timeControlStatus"]) {
    // Update your custom UI here depend on the value of `change[NSKeyValueChangeNewKey]`:
    // - AVPlayerTimeControlStatusPaused
    // - AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate
    // - AVPlayerTimeControlStatusPlaying
    AVPlayerTimeControlStatus timeControlStatus = (AVPlayerTimeControlStatus)[change[NSKeyValueChangeNewKey] integerValue];
    // ...

  } else {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  }
}

// Swift
override func observeValue(forKeyPath keyPath: String?,
                           of object: Any?,
                           change: [NSKeyValueChangeKey : Any]?,
                           context: UnsafeMutableRawPointer?)
{
  if keyPath == #keyPath(AVPlayer.timeControlStatus) {
    // Deal w/ `change?[.newKey]`
  } else {
    super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
  }
}

也是最后一个最重要的步骤,切记在不再需要观察者时将其删除,通常在-dealloc

[playerViewController.player removeObserver:self forKeyPath:@"timeControlStatus"];

顺便说一句,您还可以观察AVPlayer的rate属性,使-play等同于将rate的值设置为1.0,以及-pause等同于将rate的值设置为0.0。

但是对于您而言,我认为timeControlStatus更有意义。


有一个官方DOC供进一步阅读(但只有“准备就绪”,“失败”和“未知”状态,此处无用):"Responding to Playback State Changes"

希望有帮助。

相关问题