使用AudioToolbox framework.这个框架可以将比较短的声音注册到 system sound服务器上。被注册到systemsound服务上的声音称之为system sounds。它必须满足下面几个条件。
1、播放时间不能超过30秒。
2、数据必须是PCM或者IMA4流格式
3、必须被打包成下面三个格式之一:Core Audio Format(.caf), waveform audio(.wav),或者Audio Interchange File(.aiff)
声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:
#import <AudioToolbox/AudioToolbox.h>
@interface MediaPlayerViewController :UIViewController
IBOutletUIButton *audioButton;
SystemSoundID shortSound;
@end
#import "MediaPlayerViewController.h"
- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController"bundle:nil];
if (self)
{
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"
ofType:@"aif"];
// If this file is actually in the bundle...
if (soundPath)
{
// Create a file URL with this path
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
// Register sound file located at that URL as a system sound
OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL,
&shortSound);
if (err !=kAudioServicesNoError)
NSLog(@"Could not load %@, error code: %d", soundURL, err);
}
}
returnself;
}
这样就可以使用下面代码播放声音了:
- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
}
使用下面代码,还加一个震动的效果:
- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}