iOS設(shè)備如何監(jiān)聽音量變化呢脐往?
iOS15 停止觸發(fā)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");
}
}
不用時(shí)候要移除通知
- (void)removeVolumeNofication {
[UIApplication.sharedApplication endReceivingRemoteControlEvents];
[NSNotificationCenter.defaultCenter removeObserver:self name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
}
2吼渡、但是在使用過程中,設(shè)備升級(jí)到iOS 15.0及以后版本乓序,發(fā)現(xiàn)AVSystemController_SystemVolumeDidChangeNotification通知不觸發(fā)寺酪;可以使用KVC方法替換坎背,實(shí)現(xiàn)相應(yīng)的功能。
- (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);
}
}
記得不需要時(shí)候移除哦寄雀!
- (void)removeVolumeKVC {
[UIApplication.sharedApplication endReceivingRemoteControlEvents];
[AVAudioSession.sharedInstance removeObserver:self forKeyPath:@"outputVolume" context:nil];
}
備注:如果有更好的方法歡迎評(píng)論學(xué)習(xí)得滤!