iOS监听音量键设置

去掉系统本身自带的音量提示框

MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(-20, -20, 10, 10)];

volumeView.hidden = NO;

[self addSubview:volumeView];



-(void)initAudioSession{

NSError *error;

[[AVAudioSession sharedInstance] setActive:YES error:&error];

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ScannerClick) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];

}


- (void)dealloc{

[[NSNotificationCenter defaultCenter]removeObserver:self];

//下面这句话我用的时候暂时没有加上,加上扫描控制器就不会显示

[[UIApplication sharedApplication] endReceivingRemoteControlEvents];

}


//强制打开声音

AVAudioSession *audio = [AVAudioSession sharedInstance];

[audio setActive:YES error:nil];

为什么要强制打开,后面会说。

然后就是用自定义的提示框去顶替系统的提示框

MPVolumeView *volumeView = [[MPVolumeView alloc]initWithFrame:CGRectMake(-20, -20, 10, 10)];

volumeView.hidden = NO;

[self.view addSubview:volumeView];

这里需要注意三点:

1、需要加入MediaPlayer.framework库,然后导入头文件 #import

2、关于volumeView的hidden设置,当设置为YES是,系统还是会自动调用系统的提示框,因此必须是NO

3、最后就是把提示框的坐标放到屏幕外就可以大功告成了

**************************************************************************************************

接下来要说一下为什么强制打开声音了。

因为MPVolume的这个提示框只对处在声音开启状态时才有效,如果是静音状态下,按音量键,依旧会出提示框,因为静音是对铃声进行操作,MPVolume是对声音进行操作。

你可能感兴趣的:(iOS监听音量键设置)