iOS设备如何监听音量变化呢?
iOS15 停止触发SystemVolumeDidChangeNotification
1、在使用该功能的地方添加通知AVSystemController_SystemVolumeDidChangeNotification
- (void)addVolumeNotification
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[UIApplication.sharedApplication beginReceivingRemoteControlEvents];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(volumeChangeNotification:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
}
- (void)volumeChangeNotification:(NSNotification *)noti {
NSDictionary *userInfo = noti.userInfo;
NSString *value = [userInfo valueForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
if ([value isEqualToString:@"ExplicitVolumeChange"]) {
NSLog(@"ExplicitVolumeChange");
}
}
不用时候要移除通知
- (void)removeVolumeNofication {
[UIApplication.sharedApplication endReceivingRemoteControlEvents];
[NSNotificationCenter.defaultCenter removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
}
2、但是在使用过程中,设备升级到iOS 15.0及以后版本,发现AVSystemController_SystemVolumeDidChangeNotification通知不触发;可以使用KVC方法替换,实现相应的功能。
- (void)addVolumeKVC {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual:@"outputVolume"]) {
NSLog(@"%@", change);
}
}
记得不需要时候移除哦!
- (void)removeVolumeKVC {
[UIApplication.sharedApplication endReceivingRemoteControlEvents];
[AVAudioSession.sharedInstance removeObserver:self forKeyPath:@"outputVolume" context:nil];
}
备注:如果有更好的方法欢迎评论学习!
网友评论