【发布时间】:2011-09-14 17:03:48
【问题描述】:
我有一个正在使用 AVPlayer 构建的音频播放器。
目前,我保留 player 实例,当我需要交换曲目时(无论是手动选择还是曲目已到达终点),我创建一个新的 AVPlayerItem 并使用新的调用 replaceCurrentItemWithPlayerItem项目。
根据文档,replaceCurrentItemWithPlayerItem 是一个异步操作,所以我也观察了播放器的 currentItem 键路径。当它被调用时,我告诉我的玩家玩。
以下是相关代码:
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 上,此属性包含实际值。永远不会再次调用此方法。所以本质上,替换似乎总是失败。
这似乎是一个错误,但也许我做错了什么。
【问题讨论】:
-
Dunja 下面的回答解决了您的问题吗?
标签: objective-c ios avplayer