Objective c AVPlayer replaceCurrentItemWithPlayerItem不在iOS 4.3.3+上工作;
我有一个音频播放器,我正在建设使用AVPlayer 目前,我保留了Objective c AVPlayer replaceCurrentItemWithPlayerItem不在iOS 4.3.3+上工作;,objective-c,ios,avplayer,Objective C,Ios,Avplayer,我有一个音频播放器,我正在建设使用AVPlayer 目前,我保留了player实例,当我需要交换曲目时(无论是从手动选择还是曲目已到达末尾),我会创建一个新的AVPlayerItem,并使用新项目调用replaceCurrentItemWithPlayerItem 根据文档,replaceCurrentItemWithPlayerItem是一个异步操作,因此我还观察了播放器的currentItem键路径。当它被调用时,我告诉我的玩家去玩 以下是相关代码: AVPlayerItem *player
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];
}
}
-(void)observeValueForKeyPath:(NSString*)对象的键路径:(id)对象更改:(NSDictionary*)更改上下文:(void*)上下文{
if(context==CHStreamingAudioPlayer\u player currentitemchangedcontext){
NSLog(@“玩家当前物品已更改!更改字典:%@”,更改);
如果(_player.currentItem){
[self play];//我也遇到过类似的问题。你可能和我一样从一开始就遇到了问题。也许问题是为什么currentItem
是nil
是因为它还没有加载或准备好播放(我的问题是我无法获得新的AVPlayerItem
的持续时间)
当观察到currentItem
的状态为ReadyToPlay
时,可以尝试启动播放
AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
switch (status) {
case AVPlayerStatusUnknown: {
NSLog(@"PLAYER StatusUnknown");
}
break;
case AVPlayerStatusReadyToPlay: {
NSLog(@"PLAYER ReadyToPlay");
[self play];
}
break;
case AVPlayerStatusFailed: {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
[self handleError: [playerItem.error localizedDescription]];
}
break;
}
我不知道这是否适合你,我没有在低于或高于4.3.4的iPad上尝试过,所以我想我很快就会遇到麻烦。我在iOS 5(包括5.0.1)上遇到过这个问题。它过去在iOS 4.x上工作得很好
有两种方法可以解决此问题,每次需要交换曲目时,使用所需的AVPlayerItem
s释放并重新创建您的AVPlayerItem
。或者,只需在主线程上调用replaceCurrentItemWithPlayerItem:
我尝试了两种方法,效果都很好
积分到:邓加的以下答案是否解决了您的问题?