2012-01-06 102 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