使用AudioServicesPlaySystemSound播放一段0.2s的空白音频,并监听音频播放完成事件,如果从开始播放到回调完成方法的间隔时间小于0.1s,则意味当前静音开关为开启状态。
void SoundMuteNotificationCompletionProc(SystemSoundID ssID,void* clientData){
MMSoundSwitchDetector* detecotr = (__bridge MMSoundSwitchDetector*)clientData;
[detecotr complete];
}
- (instancetype)init {
self = [super init];
if (self) {
NSURL *pathURL = [[NSBundle mainBundle] URLForResource:@"mute" withExtension:@"caf"];
if (AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &_soundId) == kAudioServicesNoError){
AudioServicesAddSystemSoundCompletion(self.soundId, CFRunLoopGetMain(), kCFRunLoopDefaultMode, SoundMuteNotificationCompletionProc,(__bridge void *)(self));
UInt32 yes = 1;
AudioServicesSetProperty(kAudioServicesPropertyIsUISound, sizeof(_soundId),&_soundId,sizeof(yes), &yes);
} else {
MMErrorWithModule(LOGMODULE, @"Create Sound Error.");
_soundId = 0;
}
} return self;
}
- (void)checkSoundSwitchStatus:(CheckSwitchStatusCompleteBlk)completHandler {
if (self.soundId == 0) {
completHandler(YES);
return;
}
self.completeHandler = completHandler;
self.beginTime = CACurrentMediaTime();
AudioServicesPlaySystemSound(self.soundId);
}
- (void)complete {
CFTimeInterval elapsed = CACurrentMediaTime() - self.beginTime;
BOOL isSwitchOn = elapsed > 0.1;
if (self.completeHandler) {
self.completeHandler(isSwitchOn);
}
}
网友评论