iOS 9: How to change volume programmatically witho

2019-01-05 04:11发布

I have to change the volume on iPad and using this code:

[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

But this changing volume and showing system volume bar on iPad. How to change the sound without showing the volume bar?

I know, setVolume: is deprecated, and everybody says to use MPVolumeView. If this is the only way to solve my problem, then how to change the volume using MPVolumeView? I don't see any method in MPVolumeView that changes the sound.
Should I use some another class together with MPVolumeView?

But it's preferable to use MPMusicPlayerController.

Thank you for advice!

9条回答
贪生不怕死
2楼-- · 2019-01-05 04:45

You can use default UISlider with this code:

    import MediaPlayer

    class CusomViewCOntroller: UIViewController

    // could be IBOutlet
    var customSlider = UISlider()

    // in code
    var systemSlider =  UISlider()

    override func viewDidLoad() {
            super.viewDidLoad()

       let volumeView = MPVolumeView()
       if let view = volumeView.subviews.first as? UISlider{
          systemSlider = view
       }
    }

next in code just write

systemSlider.value = customSlide.value
查看更多
走好不送
3楼-- · 2019-01-05 04:50

I don't think there is any way to change the volume without flashing volume control. You should use MPVolumeView like this:

MPVolumeView* volumeView = [[MPVolumeView alloc] init];

// Get the Volume Slider
UISlider* volumeViewSlider = nil;

for (UIView *view in [volumeView subviews]){
    if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
        volumeViewSlider = (UISlider*)view;
        break;
    }
}

// Fake the volume setting
[volumeViewSlider setValue:1.0f animated:YES];
[volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
查看更多
叼着烟拽天下
4楼-- · 2019-01-05 04:57

MPVolumeView has a slider, and by changing the value of the slider, you can change the device volume. I wrote an MPVolumeView extension to easily access the slider:

extension MPVolumeView {
    var volumeSlider:UISlider {
        self.showsRouteButton = false
        self.showsVolumeSlider = false
        self.hidden = true
        var slider = UISlider()
        for subview in self.subviews {
            if subview.isKindOfClass(UISlider){
                slider = subview as! UISlider
                slider.continuous = false
                (subview as! UISlider).value = AVAudioSession.sharedInstance().outputVolume
                return slider
            }
        }
        return slider
    }
}
查看更多
登录 后发表回答