一:基本知识
播放短声音主要有两个步骤:
(1)注册声音 方法:AudioServicesCreateSystemSoundID ((CFURLRef)fileURL,&myID);
(2)播放声音 方法:AudioServicesPlaySystemSound (myID);
监听完成事件方法
AudioServicesAddSystemSoundCompletion清除播放sound ID(释放?)
AudioServicesAddSystemSoundCompletion
AudioServicesDisposeSystemSoundID (myID);
震动
可以通过System Sound API让iPhone震动,但是iPod touch不能震动。
震动可以通过指定一个特殊的system sound ID——kSystemSoundID_Vibrate实现。
方法:AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
完成短声音的播放实例,界面设计如下
运行xcode:新建项目名称为SystemSoundServices的single view application。
添加框架AudioToolbox.framework
打开ViewController.h 文件
添加头文件
打开ViewController.m 文件
添加方法 playSystemSound 和 vibrate
播放事件:
- (IBAction)playSystemSound:(id)sender { NSURL* system_sound_url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"BeepGMC500" ofType:@"wav"]]; SystemSoundID system_sound_id; AudioServicesCreateSystemSoundID( (__bridge CFURLRef)system_sound_url, &system_sound_id ); // Register the sound completion callback. AudioServicesAddSystemSoundCompletion( system_sound_id, NULL, // uses the main run loop NULL, // uses kCFRunLoopDefaultMode MySoundFinishedPlayingCallback, // the name of our custom callback function NULL // for user data, but we don't need to do that in this case, so we just pass NULL ); // Play the System Sound AudioServicesPlaySystemSound(system_sound_id); }
震动事件:
- (IBAction)vibrate:(id)sender { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); }再xib文件中完成方法的连接
回调函数实现:
void MySoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data) { AudioServicesDisposeSystemSoundID(sound_id); }