一、系统音量的监听
// 创建单例对象并且使其设置为活跃状态.
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// 需要开启该功能以便监听系统音量
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 添加监听系统音量变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
回调方法:
- (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));
}
}
}
二、耳机的插入与拔出
// 创建单例对象并且使其设置为活跃状态.
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// 添加监听耳机插入与拔出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
回调方法:
- (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
NSDictionary *interuptionDict = notification.userInfo;
NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
switch (routeChangeReason) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
//插入耳机
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
//拔出耳机
break;
}
}
网友评论