在iOS中播放简单音效的最佳方法

我发现了一些关于在iOS中播放声音的冲突数据。 我想知道是否有人可以指出我每次用户触摸屏幕时只是玩一个简单的“ping”声音的最佳方式。

谢谢!

这是在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); 

我使用这个:

头文件:

 #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 

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

(对修理audio的正确答案的小修改)

 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); }); 

您可以使用AVFoundationAudioToolbox

这里有两个分别使用库的例子。

  • SAMSoundEffect
  • BRYSoundEffectPlayer