首先需要引入头文件:
#import <AudioToolbox/AudioToolbox.h>
下面是方法
========================1.播放声音===============================
/**
* 系统铃声播放完成后的回调*/
void SystemSoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data)
{
//通过传递的SoundID,当播放完声音时,结束掉声音
}
// 播放接收到新消息时的声音
- (SystemSoundID)playNewMessageSound
{
// 要播放的音频文件地址
NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"bundle的路径" withExtension:@"bundle"];
NSURL *audioPath = [[NSBundle bundleWithURL:bundlePath] URLForResource:@"in" withExtension:@"caf"];
// 创建系统播放声音,同时标识一个声音的ID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
// 注册声音,同时监听播放完后回调。
AudioServicesAddSystemSoundCompletion(soundID,
NULL, // NULL为主循环
NULL, // 循环的模式为kCFRunLoopDefaultMode
SystemSoundFinishedPlayingCallback, // 回调函数,并播放声音
NULL // 为了data设置的,我们不需要设置,所以设置为 NULL
);
//播放声音
AudioServicesPlaySystemSound(soundID);
return soundID;
}
=========================2.播放振动==============================
// 震动
- (void)playVibration
{
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate,
NULL, // uses the main run loop
NULL, // uses kCFRunLoopDefaultMode
EMSystemSoundFinishedPlayingCallback, // 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
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}