开启监听
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//监听系统音量
[self avaVoiceNotificationMethod];
return YES;
}
音量监听+耳机监听
//音量检测
- (void)avaVoiceNotificationMethod{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:nil];
[session setActive:YES error:nil];
NSError *error;
[[AVAudioSession sharedInstance] setActive:YES error:&error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//监听系统音量变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChangeNotification:)name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
//耳机状态获取的通知
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(audioRouteChangeListenerCallback:)
name:AVAudioSessionRouteChangeNotification
object:[AVAudioSession sharedInstance]];
}
//音量变化回调
- (void)volumeChangeNotification:(NSNotification *)notifi{
float volume = [[[notifi userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
NSLog(@"系统音量:%f", volume);
}
//监听耳机插入拔出状态的改变
- (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict
valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:{//插入耳机
}
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:{//拔出耳机
}
break;
case AVAudioSessionRouteChangeReasonCategoryChange:
NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
break;
}
}
获取当前音量
//获取当前音量
- (CGFloat)getCurrentVoiceMethod{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
CGFloat currentVol = audioSession.outputVolume;
return currentVol;
}
当前耳机连接状态(包括AirPods等蓝牙音频设备)
//判断是否插入耳机
- (BOOL)hasHeadset{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *currentRoute = [audioSession currentRoute];
for (AVAudioSessionPortDescription *output in currentRoute.outputs) {
if ([[output portType] isEqualToString:AVAudioSessionPortHeadphones]||[[output portType] isEqualToString:@"BluetoothA2DPOutput"]) {
return YES;
}
}
return NO;
}
弹窗提示
//展示弹窗提示
- (void)showVoiceAlertMethod{}
//隐藏弹窗提示
- (void)hideVoiceAlertMethod{}