直接上步骤~
声音文件在这儿下载
1.引入头文件
#import <AVFoundation/AVFoundation.h>
2.声明全局的变量
/**
设置两次响的时间最小时间间隔
*/
static const CGFloat kDefaultPlaySoundInterval = 3.0;
/**
用于存储最后一次响声的时间
*/
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
3.系统声音的添加以及播放
- (void)playSoundAndVibration{
NSTimeInterval timeInterval = [[NSDate date]
timeIntervalSinceDate:self.lastPlaySoundDate];
if (timeInterval < kDefaultPlaySoundInterval) {
//如果距离上次响铃和震动时间太短, 则跳过响铃
NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
return;
}
//保存最后一次响铃时间
self.lastPlaySoundDate = [NSDate date];
// 收到消息时,播放音频
[self playNewMessageSound];
}
/**
* 系统铃声播放完成后的回调
*/
void EMSystemSoundFinishedPlayingCallingback(SystemSoundID sound_id, void* user_data)
{
AudioServicesDisposeSystemSoundID(sound_id);
}
// 播放接收到新消息时的声音
- (SystemSoundID)playNewMessageSound
{
// 要播放的音频文件地址
NSURL *audioPath = [[NSBundle mainBundle] URLForResource:@"in" withExtension:@"caf"];
// 创建系统声音,同时返回一个ID
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
// Register the sound completion callback.
AudioServicesAddSystemSoundCompletion(soundID,
NULL, // uses the main run loop
NULL, // uses kCFRunLoopDefaultMode
EMSystemSoundFinishedPlayingCallingback, // 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;
}
网友评论