導(dǎo)入頭文件
#import <AudioToolbox/AudioToolbox.h>
添加一個(gè)自己的音頻
- inFileURL : 音頻文件路徑
- outSystemSoundID:該音頻標(biāo)記的ID,為后面播放此音頻時(shí)的查找
AudioServicesCreateSystemSoundID( CFURLRef inFileURL,
SystemSoundID* outSystemSoundID)
- 實(shí)現(xiàn)案列
AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"shake_sound_male.wav" ofType:@""]]), &shakingSoundID);
替換系統(tǒng)的播放音頻
- inSystemSoundID : 添加音頻到系統(tǒng)時(shí)標(biāo)記的ID
AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)
- 播放上面的一段音頻文件
AudioServicesPlaySystemSound(shakingSoundID);
實(shí)現(xiàn)控制消息的靜音和震動(dòng)功能
邏輯:
在設(shè)置頁面放置:switch按鈕鸡挠,控制靜音和震動(dòng)按鈕祈搜,
- 靜音:播放一段沒有聲音的音頻文件
- 震動(dòng):播放一段震動(dòng)的音頻文件
使用場合:
- 聊天消息:
- 本地通知和APNS:
// 播放接收到新消息時(shí)的聲音
- (SystemSoundID)playNewMessageSound
{
// 要播放的音頻文件地址
NSString *audioStr = [[NSBundle mainBundle] pathForResource:@"right_answer" ofType:@"mp3"];
NSURL *audioPath = [[NSURL alloc] initFileURLWithPath:audioStr];
// NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"EaseMob" withExtension:@"bundle"];
// NSURL *audioPath = [[NSBundle mainBundle] pathForResource:@"right_answer" ofType:@"mp3"];
// 創(chuàng)建系統(tǒng)聲音贸辈,同時(shí)返回一個(gè)ID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(soundID,
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(soundID);
return soundID;
}
// 震動(dòng)
- (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);
}
實(shí)現(xiàn)搖一搖功能
- 設(shè)置app是否支持震動(dòng)功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
- 實(shí)現(xiàn)代理
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event ;
- 代理實(shí)現(xiàn)方式
#pragma mark - Event Delegate
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if(motion == UIEventSubtypeMotionShake) {
// 播放聲音
AudioServicesPlaySystemSound(shakingSoundID);
// AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
// 真實(shí)一點(diǎn)的搖動(dòng)動(dòng)畫
[self shaking];
}
}