How to change an iOS device volume programmatically?

前端 未结 4 580
天命终不由人
天命终不由人 2020-12-10 04:28

Is there a way to change the device volume programmatically? maybe using audio session?

相关标签:
4条回答
  • 2020-12-10 04:59

    Look at this:

    import MediaPlayer
    
    let volumeView = MPVolumeView()
    if let view = volumeView.subviews.first as? UISlider{
        view.value = 0.1 //---0 t0 1.0---
    
    }
    

    Its working for me

    0 讨论(0)
  • 2020-12-10 05:03

    I'm pretty sure that it is not possible to control the actual device volume (as this would also be a bit obtrusive) Controlling some media you're playing is another thing. You could however look into MPVolumeView: https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPVolumeView_Class/index.html for displaying a view for setting the volume.

    The question has also been discussed here: How to change device Volume on iOS - not music volume

    0 讨论(0)
  • 2020-12-10 05:10

    Hacky but works (Swift 3):

    func setVolumeTo(volume: Float) {
      (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(volume, animated: false)
    }
    

    Don't forget to import MediaPlayer

    0 讨论(0)
  • 2020-12-10 05:16

    Here you go, this worked for me.

    #import <MediaPlayer/MediaPlayer.h>
    musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
    musicPlayer.volume = 1; // max volume
    musicPlayer.volume = 0; // min volume (mute)
    musicPlayer.volume = 0.0625; // 1 bar on the overlay volume display
    
    0 讨论(0)
提交回复
热议问题