2012-08-25 68 views
1

此代碼:的iOS AVAudioPlayer不打

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"]; 
NSURL *url = [NSURL fileURLWithPath:urlPath]; 

NSError *err; 

AVAudioPlayer* audioPlayerMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err]; 

[audioPlayerMusic play]; 

作品就好了。

雖然這一個:

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"]; 
NSURL *url = [NSURL fileURLWithPath:urlPath]; 

AVPlayer* audioPlayerMusic = [AVPlayer playerWithURL:url]; 

[audioPlayerMusic play]; 

播放什麼!

怎麼回事?

+0

那麼僅僅聲明一個變量就可以工作? – 2012-08-25 21:34:45

+0

你是什麼意思?請注意,我剛更新了代碼。我做了一個複製/粘貼錯誤。 –

+0

看到我的答案。 (首先在Google上搜索類似SO的問題!) – 2012-08-25 21:51:50

回答

8

播放/流式傳輸遠程文件時,AVPlayer尚未準備好播放它 - 您必須等待它緩衝足夠的數據才能開始付費,而使用AVAudioPlayer時則不需要。所以,要麼使用AVAudioPlayer,或者讓AVPlayer使用時,它已經準備好開始播放鍵 - 值觀察通知你的類:

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

而在你的類(self是指它的實例在上面的線):

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 
    if ([keyPath isEqualToString:@"status"]) { 
     if (player.status == AVPlayerStatusReadyToPlay) { 
      [player play]; 
     } else if (player.status == AVPlayerStatusFailed) { 
      /* An error was encountered */ 
     } 
    } 
} 
+0

就是這樣。非常感謝你! –

+0

@ user1423640不客氣。 – 2012-08-25 22:04:50