美文网首页
iOS检测静音开关是否开启

iOS检测静音开关是否开启

作者: 灰斗儿 | 来源:发表于2020-03-25 12:58 被阅读0次

    使用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);
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS检测静音开关是否开启

          本文链接:https://www.haomeiwen.com/subject/itvtuhtx.html