// KVO
- (void)dealloc {
[[AVAudioSession sharedInstance] removeObserver:self
forKeyPath:NSStringFromSelector(@selector(outputVolume))];
}
- (void)addObserver {
[[AVAudioSession sharedInstance] addObserver:self
forKeyPath:NSStringFromSelector(@selector(outputVolume))
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey,id> *)change
context:(void *)context {
if ([change isKindOfClass:[NSDictionary class]]) {
NSNumber *volumeNum = change[@"new"];
if (volumeNum) {
[self volumeDidChange:[volumeNum floatValue]];
}
}
}
- (void)volumeDidChange:(CGFloat)volume {
// 显示自定义音量提示
}
// Notification
static NSNotificationName const kSystemVolumeDidChangeNotification = @"AVSystemController_SystemVolumeDidChangeNotification";
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)addObserver {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(volumeDidChange:)
name:kSystemVolumeDidChangeNotification
object:nil];
}
- (void)volumeDidChange:(NSNotification *)notification {
NSString *category = notification.userInfo[@"AVSystemController_AudioCategoryNotificationParameter"];
NSString *changeReason = notification.userInfo[@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"];
if (![category isEqualToString:@"Audio/Video"] || ![changeReason isEqualToString:@"ExplicitVolumeChange"]) {
return;
}
CGFloat volume = [[notification userInfo][@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
// 显示自定义音量提示
}