美文网首页
耳机状态的检测、监听

耳机状态的检测、监听

作者: ZJ_偶尔上路 | 来源:发表于2017-09-11 09:46 被阅读0次

当前是否存在耳机:

- (BOOL)isEarphonePluggedIn {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}

耳机状态的监听:

//监听耳机的插拔
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(earphoneStatusChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];

//相应的事件
- (void) earphoneStatusChanged:(NSNotification *)notification {
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger roteChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    
    switch (roteChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            //插入耳机
            NSLog(@"插入耳机");
            //设置屏幕亮度
             [[UIScreen mainScreen] setBrightness: 0.0];
            break;
            
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            //拔出耳机
            //设置屏幕亮度
            [[UIScreen mainScreen] setBrightness: 1.0];
            NSLog(@"拔出耳机");
            
            break;
            
    }
    
}


相关文章

网友评论

      本文标题:耳机状态的检测、监听

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