美文网首页
iOS获取及设置设备音量

iOS获取及设置设备音量

作者: 狂暴的小蜗牛 | 来源:发表于2020-07-20 11:14 被阅读0次

    设置音量相关

    1. 获取MPVolumeView

       -(MPVolumeView*)volumeView {
        if (!_volumeView) {
            _volumeView= [[MPVolumeView alloc]initWithFrame:CGRectMake(-100,-100,40,40)];
            //将x、y设置成-100就会将音量界面隐藏
            //下面两行代码都会使音量界面重新显示
            //    [_volumeView setHidden:YES];
            //     [_volumeView removeFromSuperview];
            [self.view addSubview:_volumeView];
          }
             return _volumeView;
       }
    

    2.获取MPVolumeView上面的滑条

    - (UISlider*)volumeSlider {
        UISlider* volumeSlider =nil;
         for(UIView*viewin[self.volumeViewsubviews]) {
             if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
                volumeSlider = (UISlider*)view;
                break;
        }
    }
        return volumeSlider;
    }
    

    3.设置大小:参数值范围:0~100

    - (void)setVolume:(float)value {
          self.volumeSlider = [self volumeSlider];
          // 需要设置 showsVolumeSlider 为 YES
          self.volumeView.showsVolumeSlider = YES; 
         [self.volumeSlidersetValue:value animated:NO];
         [self.volumeSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
         [self.volumeView sizeToFit];
       }
    

    获取音量大小

    1.导入头文件 #import <MediaPlayer/MediaPlayer.h>

    -(float)getVolume{
        return self.volumeSlider.value > 0 ? self.volumeSlider.value : [[AVAudioSession sharedInstance]outputVolume];
    }
    

    2.监听系统音量的变化

    使用通知监听
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(systemVolumeDidChangeNoti:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
    -(void)systemVolumeDidChangeNoti:(NSNotification* )noti{
        //目前手机音量
        float voiceSize = [[noti.userInfo valueForKey:@"AVSystemController_AudioVolumeNotificationParameter"]floatValue];
    }
    

    3.销毁监听

    -(void)dealloc{
        [[NSNotificationCenter defaultCenter]removeObserver:self];
    }

    相关文章

      网友评论

          本文标题:iOS获取及设置设备音量

          本文链接:https://www.haomeiwen.com/subject/vceekktx.html