14

我正在使用 AVPlayer 从 URL 播放音频

在 ViewDidLoad 中:

self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:imageText]];

self.player = [AVPlayer playerWithPlayerItem:playerItem];

[player addObserver:self forKeyPath:@"status" options:0 context:nil];

[player play];

观察者

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {
    if (object == player && [keyPath isEqualToString:@"status"]) {
        if (player.status == AVPlayerStatusReadyToPlay) {
            //[playingLbl setText:@"Playing Audio"];
            NSLog(@"fineee");
            [playBtn setEnabled:YES];
        } else if (player.status == AVPlayerStatusFailed) {
            // something went wrong. player.error should contain some information
            NSLog(@"not fineee");
            NSLog(@"%@",player.error);

        }
        else if (player.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");


        }
    }
}

但是播放器有时会卡住并且不播放音频,但状态也是 AVPlayerStatusReadyToPlay。它永远不会进入 AVPlayerStatusFailed 或 AVPlayerItemStatusUnknown 内部。因为我想处理 AVPlayer 的错误,它也必须进入这些内部。请帮忙!!

4

1 回答 1

32

您应该观察 CurrentItem 的状态。AVPlayer 因 AVPlayerItem 失败而失败,如果出现任何问题,则从 AVPlayerItem 开始,然后是 AVPlayer。

尝试:

[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

在你的 observeValueForKeyPath 中:

if (object == audioPlayer.currentItem && [keyPath isEqualToString:@"status"]) {
    if (audioPlayer.currentItem.status == AVPlayerItemStatusFailed) {
        NSLog(@"------player item failed:%@",audioPlayer.currentItem.error);
    }
}

你可以看看 AVPlayer 的处理方式,或者直接从我的开源项目HysteriaPlayer中使用它。

于 2013-02-26T10:19:40.510 回答