观察和响应播放变化的一种简单方法是使用键值观察 (KVO)。在您的情况下,请注意 AVPlayer 的 timeControlStatus 或 rate 属性。
例如:
{
// 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 更有意义。
有一个官方文档供进一步阅读(但只是“准备播放”、“失败”和“未知”状态,在这里没用):"Responding to Playback State Changes"。
希望对你有帮助。