2011-04-16 123 views
0

我想在我的應用程序中播放聲音,我正在使用.mp3文件類型。它在模擬器中工作正常,但是當我將它發送到我的設備時,它不工作並且沒有產生任何聲音,任何人都無法幫助我爲什麼它不能在設備上工作或哪種文件格式更適合在iPhone和iPad中播放音頻文件?在iPhone/iPad應用程序中播放音頻文件?

NSURL *tapSound = [[NSBundle mainBundle] URLForResource: [NSString stringWithFormat:@"%@",SoundFileName] withExtension: @""]; 

// Store the URL as a CFURLRef instance 
self.soundFileURLRef = (CFURLRef) [tapSound retain]; 

// Create a system sound object representing the sound file. 
AudioServicesCreateSystemSoundID (
        soundFileURLRef, 
        &soundFileObject 
        ); 

AudioServicesPlaySystemSound (soundFileObject); 

以上是我的代碼來播放聲音

謝謝。

+0

@ user532445,或者如果沒有人發佈可接受的答案,則將答案發布到您自己的問題中,以便您在開發過程中繼續前進。這樣你就回到了SO。 – 2011-04-16 13:40:46

回答

0

如果設備靜音,系統聲音ID將不會播放,所以這可能是原因。 (它們只是用於用戶界面效果的目的,如警報等,按照official documentation。)

因此,我會試圖使用AVAudioPlayer風格的方法。作爲示例(無雙關語)實現:

// *** In your interface... *** 
#import <AVFoundation/AVFoundation.h> 

... 

AVAudioPlayer *testAudioPlayer; 

// *** Implementation... *** 

// Load the audio data 
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sample_name" ofType:@"wav"]; 
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath]; 
NSError *audioError = nil; 

// Set up the audio player 
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError]; 
[sampleData release]; 

if(audioError != nil) { 
    NSLog(@"An audio error occurred: \"%@\"", audioError); 
} 
else { 
    [testAudioPlayer setNumberOfLoops: -1]; 
    [testAudioPlayer play]; 
} 



// *** In your dealloc... *** 
[testAudioPlayer release]; 

您還應該記得設置適當的音頻類別。 (請參閱AVAudioSessionsetCategory:error:方法。)

最後,您需要將AVFoundation庫添加到您的項目中。爲此,請在Xcode的Groups & Files列中單擊您的項目目標,然後選擇「Get Info」。然後選擇常規選項卡,單擊底部「鏈接庫」窗格中的+並選擇「AVFoundation.framework」。

0

我誠實地建議使用AVAudioPlayer代替這個,但你可以嘗試使用這個替代代碼。在你的例子中,它看起來像忘了包含擴展名,這也可能是問題。模擬器在命名上更加寬鬆,所以如果您忘記了擴展名,它可能會在模擬器上播放,而不是設備。

SystemSoundID soundFileObject; 
CFURLRef soundFileURLRef = CFBundleCopyResourceURL (CFBundleGetMainBundle(),CFSTR ("sound"),CFSTR ("mp3"),NULL); 
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject); 
AudioServicesPlaySystemSound (soundFileObject);