当前是否存在耳机:
- (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;
}
}
网友评论