在 iOS15 中,不再调用 @"AVSystemController_SystemVolumeDidChangeNotification" 通知。
改用键值观察。(扩展上面马特的回答)
在您的 ViewController.m 文件中
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController : UIViewController
{
AVAudioSession *audioSession;
}
@end
在您的 View Controller.m 文件中
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:YES error:nil];
[audioSession addObserver:self forKeyPath:@"outputVolume" options:0 context:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[audioSession removeObserver:self forKeyPath:@"outputVolume"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
CGFloat newVolume = audioSession.outputVolume;
NSLog(@"newVolume: %f", newVolume);
//if the volume gets to max or min observer won't trigger
if (newVolume > 0.9 || newVolume < 0.1) {
[self setSystemVolume:0.5];
return;
}
}
//set the volume programatically
- (void)setSystemVolume:(CGFloat)volume {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[MPMusicPlayerController applicationMusicPlayer] setVolume:(float)volume];
#pragma clang diagnostic pop
}
您可以使用移出屏幕的 MPVolumeView 隐藏音量滑块。
使用 MPVolumeView 滑块调整音量时隐藏设备音量 HUD 视图