2012-11-29 27 views
4

我試圖寫一些非常簡單的代碼來播放音頻文件。該代碼在iPad2模擬器上正常工作。然而,在我的iPad2設備上,[audooPlayer play]返回false,不會聽到任何音頻。AVAudioPlayer播放在硬件上返回false

我試過了.caf和.wav文件。我重新啓動了iPad2並確保靜音開關關閉。如何調試的任何提示大大讚賞。

示例代碼:

- (void)playAudio { 
    NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"wav"]; 
    url = [NSURL fileURLWithPath:file]; 
    NSError *error = nil; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    if (error != nil) { 
     NSLog(@"Error creating audio player: %@", [error localizedDescription]); 
     return; 
    } 
    [audioPlayer setDelegate:self]; 
    if (![audioPlayer prepareToPlay]) { 
     NSLog(@"Error preparing audio"); 
     return; 
    } 
    // Everything works fine up to this point 
    if (![audioPlayer play]) { 
     // I hit this on hardware. Works perfect on the simulator. 
     NSLog(@"Error playing audio"); 
     return; 
    } 
+1

我已經在iPhone模擬器和iPhone設備上測試了你的代碼(都是iOS 6.0),它工作正常!我沒有iPad設備。你的錯誤是什麼?你的'audioPlayerDecodeErrorDidOccur'被調用了嗎? – sunkehappy

+1

謝謝你的幫助。您的結果幫助我意識到問題在其他地方 - 請參閱下面的答案。 – Brad

+0

我已經在iPhone模擬器上測試您的代碼,它工作正常! 但在真實設備中無法使用。 :(( –

回答

12

太多調試後,我終於找到了罪魁禍首。我正在按照http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html#//apple_ref/doc/uid/TP40009767-CH2的指南進行操作,在播放音頻之前在我的應用程序中,我錄製了一些音頻。根據該指南,我打電話給

[[AVAudioSession sharedInstance] setActive: NO error: nil]; 

完成記錄時。這顯然會導致AVAudioPlayer無法播放音頻。將呼叫更改爲

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; 

反而修復了一些問題。奇怪的是,這在模擬器中並不是問題,但會在硬件上造成問題。

+1

)非常感謝你,我永遠不會發現這個, – Linuxios

+0

同上,非常感謝你爲我節省了調試時間! – mbm29414