草庐IT

objective-c - AVPlayer replaceCurrentItemWithPlayerItem 不适用于 iOS 4.3.3+

coder 2023-07-26 原文

我有一个使用 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 中,此属性包含实际值。永远不会再次调用此方法。所以本质上,替换似乎总是失败。

这似乎是一个错误,但也许我做错了什么。

最佳答案

我在使用 iOS 5(包括 5.0.1)时遇到了这个问题。它曾经在 iOS 4.x 上运行良好。

有两种方法可以解决这个问题,每次您需要交换轨道时,释放并使用所需的 AVPlayerItem 重新创建您的 AVPlayer。或者,只需在主线程上调用 replaceCurrentItemWithPlayerItem:

我尝试了这两个选项,它们运行良好。

致谢:Apple Developer Forums

关于objective-c - AVPlayer replaceCurrentItemWithPlayerItem 不适用于 iOS 4.3.3+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7420176/

有关objective-c - AVPlayer replaceCurrentItemWithPlayerItem 不适用于 iOS 4.3.3+的更多相关文章

随机推荐