有没有使用AudioToolBox框架播放短声音的代码片段?如果您能与我和社区分享,我将不胜感激。我在其他地方查找的代码看起来都不太清晰。
谢谢!
有没有使用AudioToolBox框架播放短声音的代码片段?如果您能与我和社区分享,我将不胜感激。我在其他地方查找的代码看起来都不太清晰。
谢谢!
这是一个使用AVAudioPlayer的简单示例:
-(void)PlayClick
{
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"click"
ofType:@"caf"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[click play];
[click release];
}
这假设主包中有一个名为 "click.caf" 的文件。因为我经常播放这个声音,所以我实际上会保留它以便稍后播放它,而不是立即释放它。
我写了一个简单的Objective-C封装,围绕着 AudioServicesPlaySystemSound
和相关内容:
#import <AudioToolbox/AudioToolbox.h>
/*
Trivial wrapper around system sound as provided
by Audio Services. Don’t forget to add the Audio
Toolbox framework.
*/
@interface Sound : NSObject
{
SystemSoundID handle;
}
// Path is relative to the resources dir.
- (id) initWithPath: (NSString*) path;
- (void) play;
@end
@implementation Sound
- (id) initWithPath: (NSString*) path
{
[super init];
NSString *resourceDir = [[NSBundle mainBundle] resourcePath];
NSString *fullPath = [resourceDir stringByAppendingPathComponent:path];
NSURL *url = [NSURL fileURLWithPath:fullPath];
OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle);
NSAssert1(errcode == 0, @"Failed to load sound: %@", path);
return self;
}
- (void) dealloc
{
AudioServicesDisposeSystemSoundID(handle);
[super dealloc];
}
- (void) play
{
AudioServicesPlaySystemSound(handle);
}
@end
来源: AudioServices - iPhone Developer Wiki
AudioService 声音不受设备音量控制器的影响。即使手机处于静音模式,也会播放 Audio service 声音。只有通过进入设置 -> 声音 -> 铃声和提示音 才能将这些声音静音。
可以使用以下代码播放自定义系统声音:
CFBundleRef mainbundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainbundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
AudioServicesPlaySystemSound(1100);