方法一,使用通知:
1、添加监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeDidChange:)name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
2、添加执行方法
- (void)volumeDidChange:(NSNotification *)notification
{
DDLogInfo(@"%@-%@,点击音量键静音", THIS_FILE, THIS_METHOD);
}
3、销毁的时候,移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
方法二,使用KVO:
1、添加KVO
[[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:(void *)[AVAudioSession sharedInstance]];
2、实现方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if(context == (__bridge void *)[AVAudioSession sharedInstance]){
float newValue = [[change objectForKey:@"new"] floatValue];
float oldValue = [[change objectForKey:@"old"] floatValue];
// TODO: 这里实现你的逻辑代码
}
}
3、销毁的时候,移除KVO
[[AVAudioSession sharedInstance] removeObserver:self forKeyPath:@"outputVolume" context:(void *)[AVAudioSession sharedInstance]];
锁屏监听音量键: