9

Ok,

This gets the system volume, works well.

var volume = AVAudioSession.sharedInstance().outputVolume
print("output volume: \(volume)")

But how do I set the system volume [in Swift] please

user3069232
  • 8,587
  • 7
  • 46
  • 87

2 Answers2

15

Here is what you need to do with latest iOS 10.2

Step 1. Import MediaPlayer

import MediaPlayer

Step 2. Add extension

//Update system volume
extension MPVolumeView {
    static func setVolume(_ volume: Float) {
        let volumeView = MPVolumeView()
        let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
            slider?.value = volume
        }
    }
}

Step 3. Change volume this way

 //Update system volume
 MPVolumeView.setVolume(0.2)

Thanks to trungduc

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
10

First you need to import media player like,

import MediaPlayer

Then you can set the system volume like,

let volumeView = MPVolumeView()
if let view = volumeView.subviews.first as? UISlider
{
     view.value = 0.1   // set b/w 0 t0 1.0       
}

Hope this will help you.

Jigar Tarsariya
  • 3,189
  • 3
  • 14
  • 38
  • 1
    It seems to work, but AVAudioSession.sharedInstance().outputVolume still reports the volume with the same value, so perhaps this is not quite the answer I was looking for? – user3069232 Jun 17 '16 at 07:04
  • How to hide volume hud? I tried view.isHidden = false and volumeView.isHidden, but no luck... – Yaroslav Dukal Oct 04 '16 at 10:05
  • This works pretty well. Anyone know how Apple feels about wrt App Review? – drewster Jul 24 '18 at 19:15
  • I've seen a lot of apps that do this, and they made it through app review. That said, I'm sure Apple doesn't like it, or they'd give us a real API. As far as hiding it, I know in the past, you used to be able to hide it by setting opacity or alpha to 0.01 or something like that. Haven't tried recently. – drewster Jan 17 '20 at 06:47
  • 1
    Doesn't work for me – Xys Mar 28 '22 at 16:17
  • It does not work tried on XCode 13.2.1 with Swift 5.5, but the upper one works fine – Vinod May 19 '22 at 11:05