2013-02-18 76 views
13

我使用AVPlayer從URLAVPlayer狀態始終AVPlayerStatusReadyToPlay

在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的錯誤,它也必須進入這些內部。請幫忙!!

回答

31

您應該觀察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,我的開源項目中使用它。

+0

超級感謝:)你是救星:) – Srikanth 2015-11-05 04:49:45

+0

謝謝!這段代碼幫助了我! – 2016-03-21 19:07:43

+0

**準確**我在找什麼,謝謝! – zpasternack 2016-05-05 05:53:16