2013-05-08 120 views
3

我在這裏找到了很多解決方案,但是由於某些原因,所有這些解決方案都無法產生任何聲音。如何在iOS中播放聲音?

這裏是我當前的代碼:

PRE: I've added AudioToolbox.framework and imported <AVFoundation/AVFoundation.h> in my .m file 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSURL* sndurl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"aif"]; 
    SystemSoundID snd; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)sndurl, &snd); 
    AudioServicesAddSystemSoundCompletion(snd, nil, nil, SoundFinished, nil); 
    AudioServicesPlaySystemSound(snd); 
} 

void SoundFinished (SystemSoundID snd, void* context) { 
     AudioServicesRemoveSystemSoundCompletion(snd); 
     AudioServicesDisposeSystemSoundID(snd); 
} 

該解決方案是直出書。但是當我運行該項目時,如果不能產生任何聲音。我的文件是test.aif,長度爲5秒。

任何建議爲什麼它不起作用?如果這不是最好的解決方案,你如何在iOS6上製作聲音?

+1

確保硬件靜音開關已關閉。系統聲音在無聲模式下關閉。 – 2013-05-08 21:13:11

回答

6

根據this topic等,播放音頻片段可以像下面這樣簡單,我使用的方法(函數)。我自己做過。

- (void)playAudio { 
    [self playSound:@"pageflip1" :@"wav"]; 
} 

- (void)playSound :(NSString *)fName :(NSString *) ext{ 
    SystemSoundID audioEffect; 
    NSString *path = [[NSBundle mainBundle] pathForResource : fName ofType :ext]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath : path]) { 
     NSURL *pathURL = [NSURL fileURLWithPath: path]; 
     AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect); 
     AudioServicesPlaySystemSound(audioEffect); 
    } 
    else { 
     NSLog(@"error, file not found: %@", path); 
    } 
} 
+0

您的代碼返回路徑變量的「(空)」。我無法弄清楚爲什麼。 – 2013-05-08 21:59:51

+0

將您的音頻文件拖放到項目邊欄中。 – 2013-05-08 22:04:31

+0

感謝!我認爲添加文件時沒有選擇「添加到目標」複選框。它應該被選中。 – 2013-05-08 22:08:15

0

請務必嘗試在實際設備上測試它,因爲模擬器在使用AVFoundation時可能會遇到問題。