2012-01-06 57 views
1

我試圖播放聲音的按鈕點擊我使用:聲音不玩xcode?

-(IBAction)sound { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"wav"]; 
      AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
      theAudio.delegate = self; 
      [theAudio play]; 
} 

;及

#import <AVFoundation/AVAudioPlayer.h> 

.h file;

- (IBAction) sound; 

做我忘帶了什麼東西?

回答

2

我以前有過這個問題,而且由於ARC工作的新方式,這是令人驚訝的欺騙性。

您已經在方法「sound」中創建了音頻。但是,此對象的使用壽命只會持續到方法退出。因此,在它甚至有機會播放聲音之前,ARC會破壞音頻。有趣的是,如果你在ARC之前這樣做,你會發現你的聲音播放,但你有內存泄漏,因爲音頻沒有被釋放。或者你可以在回調發生時釋放它,但這種做法違反了一些內存管理原則,所以我不會支持它。

您將需要某種類型的「混音器」類來處理/持續音頻播放器組。

+0

感謝的人導入音頻工具箱,你幫了我:) – 2015-05-14 21:16:29

1

試試這個,並確保在您的.h文件中

CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"H1", CFSTR("WAV"), NULL); 
if (soundFileURLRef){ 
CFStringRef url = CFURLGetString(soundFileURLRef); 
} 
UInt32 soundID; 
AudioServicesCreateSystemSoundID)soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound(soundIB); 
+0

好的代碼!有幾個錯別字。這裏是固定代碼: CFBundleRef mainBundle = CFBundleGetMainBundle(); (CFBtring,CFStringRef)@「MySoundFile」,CFSTR(「aif」),NULL);或者,CFURLRef UInt32 soundID; AudioServicesCreateSystemSoundID(soundFileURLRef,&soundID); AudioServicesPlaySystemSound(soundID); – 2015-02-09 07:10:42