一、系統(tǒng)音量的監(jiān)聽
// 創(chuàng)建單例對象并且使其設(shè)置為活躍狀態(tài).
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// 需要開啟該功能以便監(jiān)聽系統(tǒng)音量
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 添加監(jiān)聽系統(tǒng)音量變化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
回調(diào)方法:
- (void)onVolumeChanged:(NSNotification *)notification {
if ([[notification.userInfo objectForKey:@"AVSystemController_AudioCategoryNotificationParameter"] isEqualToString:@"Audio/Video"]) {
if ([[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"] isEqualToString:@"ExplicitVolumeChange"]) {
CGFloat volume = [[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
NSLog(@"volume: %@", @(volume));
}
}
}
二、耳機(jī)的插入與拔出
// 創(chuàng)建單例對象并且使其設(shè)置為活躍狀態(tài).
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// 添加監(jiān)聽耳機(jī)插入與拔出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
回調(diào)方法:
- (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
//插入耳機(jī)
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
//拔出耳機(jī)
break;
}
}