我正在使用AVPlayer播放来自网址的音频
在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的错误,它也必须进入这些错误。请帮忙!!
答案 0 :(得分:32)
您应该观察CurrentItem的状态。由于AVPlayerItem失败,AVPlayer失败,如果出现任何错误,则从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中使用它。