1.在Appdelegate中的添加监听
-(void)applicationDidBecomeActive:(UIApplication *)application{
NSLog(@"唤醒");
self.Bool_Sub = false;//是否是减操作
self.Bool_Add = false;//是否是加操作
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];//监听系统音量变化
2022-05-23-1631-更新:
1.iOS15后改为 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"SystemVolumeDidChange" object:nil];//监听系统音量变化
注意:收到的铃声或者从后台进入前台,通知方法都会触发。通过判断Reason 来判断当前通知是由什么触发
NSString * reasonStr = [notification.userInfo objectForKey:@"Reason"];
if([reasonStr isEqualToString:@"ExplicitVolumeChange"]) {
//输入你要做的事
}
[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryAmbient error:nil];//设置媒体音频类型-解释自行搜索AVAudioSession
[[AVAudioSession sharedInstance]setActive:YES error:nil];//截获设置
[[UIApplication sharedApplication]beginReceivingRemoteControlEvents];//开始接收所有触发,否则监听无反应
self.systemValue = [[AVAudioSession sharedInstance]outputVolume];//获取当前输出音量值(系统音量)
}
2.移除相关监听
-(void)applicationDidEnterBackground:(UIApplication *)application{
NSLog(@"后台");
[[AVAudioSession sharedInstance]setActive:NO error:nil];
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
[[UIApplication sharedApplication]endReceivingRemoteControlEvents];
}
3.创建系统音量控制调,获取控制滑块【头文件:#import
-(MPVolumeView *)volumeView{//这个最好在VC上重写,在window上写,可能会出现一次。在window上写只是为了获取音量滑块
if (!_volumeView) {
_volumeView = [[MPVolumeView alloc]initWithFrame:CGRectMake(-100, -100, 40, 40)];
_volumeView.showsRouteButton = NO;
[self.window addSubview:_volumeView];
}
return _volumeView;
}
-(UISlider *)volumeSlider{
UISlider* volumeSlider =nil;
for (UIView * subView in self.volumeView.subviews) {
if ([subView.class.description isEqualToString:@"MPVolumeSlider"]) {
volumeSlider = (UISlider*)subView;
break;
}
}
returnvolumeSlider;
}
4.监听方法
-(void)onVolumeChanged:(NSNotification *)notification{
if ([[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"] isEqualToString:@"ExplicitVolumeChange"]) {
CGFloat volume = [[notification.userInfo objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
// NSLog(@"volume==%lf self.systemValue==%lf ",volume,self.systemValue);
if(volume>self.systemValue) {
NSLog(@"加-------------------------------加----222");
self.Bool_Add=true;
}elseif(volume
self.Bool_Sub=true;
NSLog(@"减-------------------------------减----2222");
}else if (self.systemValue == 1) {
if(self.Bool_Sub==false&& volume ==1) {
NSLog(@"加-------------------------------加");
}else{
self.Bool_Sub=false;
}
}else if(self.systemValue == 0){
if(volume ==0&&self.Bool_Add==false) {
NSLog(@"减-------------------------------减");
}else{
self.Bool_Add=false;
}
}
self.volumeSlider.value = self.systemValue;//将原始系统音量重新给系统滑块,以达到不改变系统音量的情况下通过音量加减键调节app音量值。
}
}