[英]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.