11

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

DrCachetes
  • 954
  • 1
  • 9
  • 30

4 Answers4

5

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

Community
  • 1
  • 1
Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47
2

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

Abdul Yasin
  • 3,480
  • 1
  • 28
  • 42
1

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
Liam Hardy
  • 246
  • 1
  • 7
  • 1
    That changes the relative volume of the media you're playing, but I'm pretty sure the actual volume ranges from 0 to the user's current volume setting. So if the user has the volume set to 1/2, your musicPlayer.volume setting of 1.0 would actually give you 1/2 volume. – Duncan C Mar 14 '15 at 15:02
  • 4
    that is deprecated from ios7 – Mitul Bhadeshiya Jul 24 '15 at 10:42
1

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

budiDino
  • 13,044
  • 8
  • 95
  • 91
  • This actually works! Just make sure to do `import MediaPlayer` at the top. – Youssef Moawad Oct 02 '17 at 18:19
  • I got a downvote so I assume it doesn't work on some newer iOS. If someone ends up testing this, let us know here in the comments which iOS you are running on. Thank you ;) – budiDino Dec 21 '18 at 03:46