2012-03-20 39 views

回答

25

这是打一个简单的声音在iOS中(不超过30秒)的最佳方式:

//Retrieve audio file 
NSString *path = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"]; 
NSURL *pathURL = [NSURL fileURLWithPath : path]; 

SystemSoundID audioEffect; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect); 
AudioServicesPlaySystemSound(audioEffect); 

// call the following function when the sound is no longer used 
// (must be done AFTER the sound is done playing) 
AudioServicesDisposeSystemSoundID(audioEffect); 
+0

我只是做这个自己。 – 2012-03-20 21:18:29

+0

谢谢!有效! – noloman 2013-08-22 10:15:27

+0

谢谢兄弟!其作品.. – 2015-01-05 05:54:51

29

我用这个:

头文件:

#import <AudioToolbox/AudioServices.h> 

@interface SoundEffect : NSObject 
{ 
    SystemSoundID soundID; 
} 

- (id)initWithSoundNamed:(NSString *)filename; 
- (void)play; 

@end 

源文件:

#import "SoundEffect.h" 

@implementation SoundEffect 

- (id)initWithSoundNamed:(NSString *)filename 
{ 
    if ((self = [super init])) 
    { 
     NSURL *fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil]; 
     if (fileURL != nil) 
     { 
      SystemSoundID theSoundID; 
      OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID); 
      if (error == kAudioServicesNoError) 
       soundID = theSoundID; 
     } 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    AudioServicesDisposeSystemSoundID(soundID); 
} 

- (void)play 
{ 
    AudioServicesPlaySystemSound(soundID); 
} 

@end 

您将需要创建一个SoundEffect实例并直接调用该方法。

+0

这太好了。我使用的是SystemSoundID的C数组,但是我只是碰到了schlepp需要处理的一点。切换到基于此的东西。谢谢! – 2012-10-19 23:46:42

+2

虽然这不适用于ARC。为了在ARC中使用它,你必须添加一个完成回调函数,你可以在这里处理systemsound。如果你在dealloc中这样做,声音立即死亡: 'AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,completionCallback,(__bridge_retained void *)self);' 像这样的例子 – Maverick1st 2013-04-08 15:07:32

+0

@ Maverick1st这与ARC非常吻合,必须确保你的'SoundEffect'对象不会立即被释放,比如将它分配给一个属性。 – shawkinaw 2013-07-26 22:15:03

10

(小修改正确的答案照顾音频的处置)

NSString *path = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"]; 
NSURL *pathURL = [NSURL fileURLWithPath : path]; 

SystemSoundID audioEffect; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect); 
AudioServicesPlaySystemSound(audioEffect); 
// Using GCD, we can use a block to dispose of the audio effect without using a NSTimer or something else to figure out when it'll be finished playing. 
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
    AudioServicesDisposeSystemSoundID(audioEffect); 
}); 
+1

这是异步播放声音的最佳方式。 – alones 2014-12-11 02:19:46

相关问题