開(kāi)啟監(jiān)聽(tīng)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//監(jiān)聽(tīng)系統(tǒng)音量
[self avaVoiceNotificationMethod];
return YES;
}
音量監(jiān)聽(tīng)+耳機(jī)監(jiān)聽(tīng)
//音量檢測(cè)
- (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];
//監(jiān)聽(tīng)系統(tǒng)音量變化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChangeNotification:)name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
//耳機(jī)狀態(tài)獲取的通知
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(audioRouteChangeListenerCallback:)
name:AVAudioSessionRouteChangeNotification
object:[AVAudioSession sharedInstance]];
}
//音量變化回調(diào)
- (void)volumeChangeNotification:(NSNotification *)notifi{
float volume = [[[notifi userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
NSLog(@"系統(tǒng)音量:%f", volume);
}
//監(jiān)聽(tīng)耳機(jī)插入拔出狀態(tài)的改變
- (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict
valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:{//插入耳機(jī)
}
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:{//拔出耳機(jī)
}
break;
case AVAudioSessionRouteChangeReasonCategoryChange:
NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
break;
}
}
獲取當(dāng)前音量
//獲取當(dāng)前音量
- (CGFloat)getCurrentVoiceMethod{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
CGFloat currentVol = audioSession.outputVolume;
return currentVol;
}
當(dāng)前耳機(jī)連接狀態(tài)(包括AirPods等藍(lán)牙音頻設(shè)備)
//判斷是否插入耳機(jī)
- (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{}