我正在使用AVPlayer从URL播放音频
@H_403_13@解决方法@H_502_14@
在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的错误,它也必须在这些内.请帮忙!!
您应该遵守CurrentItem的状态. AVPlayer失败,因为AVPlayerItem失败,如果anythings出错,它从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开源项目使用它.