[英]How to detect the toggle on the display of playback controls with AVPlayerViewController?
我想知道是否可以检测播放控件何时从 AVPlayerViewController 视图中出现或消失。 我正在尝试在我的播放器上添加一个 UI 元素,该元素必须遵循播放控件显示。 仅在显示控件时出现,否则消失
我似乎没有找到任何可以在 AVPlayerViewController 上观察到的值来实现这一点,也没有任何回调或委托方法。
我的项目在 Swift 中。
观察和响应播放变化的一种简单方法是使用键值观察(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
更有意义。
有一个官方文档供进一步阅读(但只是“准备播放”、“失败”和“未知”状态,在这里没用): “响应播放状态更改” 。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.