ios 监听及改变系统音量

ios13.0 后修改系统音量

if (([musicPlayer respondsToSelector:@selector(setVolume:)]) && [[[UIDevice currentDevice] 
     systemVersion] floatValue] >= 13.0) {
//消除警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            
            [musicPlayer setVolume:volume];
            
#pragma clang diagnostic pop
            
     }

ios13.0 之前修改系统音量

MPVolumeView *volumeView = [[MPVolumeView alloc] init];
volumeView.frame = CGRectMake(-1000, -100, 100, 100);
UISlider* volumeViewSlider = nil;
for (UIView *view in [volumeView subviews]){
    if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
        volumeViewSlider = (UISlider*)view;
        break;
    }
}
[volumeViewSlider setValue:volume animated:YES];

ios 监听系统音量

if (@available(iOS 15.0,*)) {
    AVAudioSession *audio = [AVAudioSession sharedInstance];
    [audio addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
}else{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
}


  // 监听音量改变
 -(void)volumeChanged:(NSNotification *)notification{
    self.volum = [[[notification userInfo] objectForKey:@"AVSystemController_SystemVolumeDidChangeNotification"] floatValue];

}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
   if ([keyPath isEqual:@"outputVolume"]) {
   //        NSLog(@"%@", change);
    self.volum = [[change objectForKey:@"new"] floatValue];
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容