AVPlayer replaceCurrentItemWithPlayerItem不适用于iOS 4.3.3+ [英] AVPlayer replaceCurrentItemWithPlayerItem not working on iOS 4.3.3+
问题描述
我有一个使用AVPlayer构建的音频播放器。
I have an audio player that I'm building using AVPlayer.
目前,我保留播放器
实例和我需要交换轨道时(从手动选择或轨道到达结束)我创建一个新的 AVPlayerItem
我打电话给 replaceCurrentItemWithPlayerItem
使用新项。
Currently, I keep the player
instance around and when I need to swap tracks (either from a manual selection or the track has reached the end) I create a new AVPlayerItem
and I call replaceCurrentItemWithPlayerItem
with the new item.
根据文档, replaceCurrentItemWithPlayerItem
是异步的操作,所以我也观察了播放器的 currentItem 键路径。当它被调用时,我告诉我的玩家玩。
According to the docs, replaceCurrentItemWithPlayerItem
is an asynchronous operation, so I also observe the currentItem key path of the player. When that gets called, I tell my player to play.
以下是相关代码:
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerItemStatusChangedContext];
if (!_player) {
_player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerStatusChangedContext];
[_player addObserver:self forKeyPath:@"currentItem" options:NSKeyValueObservingOptionNew context:CHStreamingAudioPlayer_PlayerCurrentItemChangedContext];
} else {
[_player replaceCurrentItemWithPlayerItem:playerItem];
}
这是键值观察回调:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == CHStreamingAudioPlayer_PlayerCurrentItemChangedContext) {
NSLog(@"Player's current item changed! Change dictionary: %@", change);
if (_player.currentItem) {
[self play]; //<---- doesn't get called
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
在iOS 4.3.3(和iOS 5)上我的调用密钥观察方法,但 _player.currentItem
总是 nil
。在4.2.1和4.3.2上,此属性包含实际值。永远不会再调用此方法。所以从本质上讲,替换似乎总是失败。
On iOS 4.3.3 (and iOS 5) my key observation method is called but _player.currentItem
is always nil
. On 4.2.1 and 4.3.2 this property contains the actual value. This method is never called again. So in essence, replacing seems to always fail.
这似乎是一个错误,但也许我做错了。
This seems like a bug, but perhaps I'm doing something wrong.
推荐答案
我在iOS 5(包括5.0.1)中遇到过这个问题。它曾经在iOS 4.x上正常工作。
I had this issue with iOS 5 (including 5.0.1). It used to work fine on iOS 4.x.
有两种解决方法,使用所需的释放并重新创建
s。或者,只需在主线程上调用 AVPlayer
每次需要交换曲目时,AVPlayerItem replaceCurrentItemWithPlayerItem:
。
There are two ways to workaround this, release and recreate your AVPlayer
with the desired AVPlayerItem
s each time you need to swap tracks. Or, simply call replaceCurrentItemWithPlayerItem:
on the main thread.
我尝试了两种选择,但它们运行良好。
I tried both options and they worked fine.
这篇关于AVPlayer replaceCurrentItemWithPlayerItem不适用于iOS 4.3.3+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!