49

My case is simple: I need to play a warning signal and want to make sure the user will hear it, so I want to check the system volume.

How can I find out what the current system volume is?

8 Answers8

50

Update for Swift

let vol = AVAudioSession.sharedInstance().outputVolume

The audio session can provide output volume (iOS >= 6.0).

float vol = [[AVAudioSession sharedInstance] outputVolume];
NSLog(@"output volume: %1.2f dB", 20.f*log10f(vol+FLT_MIN));
aturan23
  • 4,798
  • 4
  • 28
  • 52
papahabla
  • 1,448
  • 18
  • 18
  • I use in iOS 11 in today extension - sometimes it doesn't work – Vyachaslav Gerchicov May 21 '18 at 15:13
  • https://stackoverflow.com/questions/24872409/avaudiosessions-outputvolume-never-changes/52284131#52284131 -try playing audio then checking. Had same proble, worked for me. – Tom Andersen Sep 12 '18 at 13:42
  • Make sure to also do `AVAudioSession.sharedInstance().setActive(true)` first or this value will not update when the volume is changed – rolling_codes Jan 10 '20 at 20:30
  • Just a little niggle: the value returned is not a ratio/gain which can be directly converted to decibels like this. The value directly reflects the position of the volume indicator, and Apple aren't advertising how that relates to an actual gain or decibel value. Most likely it's a scale mapped to a decibel range, but it's anyone's guess what the scale is. – Michael Tyson Apr 20 '20 at 23:40
16

Swift 3.1

let audioSession = AVAudioSession.sharedInstance()
var volume: Float?
do {
    try audioSession.setActive(true)
    volume = audioSession.outputVolume
} catch {
    print("Error Setting Up Audio Session")
}

audioSession.setActive(true) - important

Vasilii Muravev
  • 3,063
  • 17
  • 45
13

Try this:

MPMusicPlayerController *iPod = [MPMusicPlayerController iPodMusicPlayer];
float volumeLevel = iPod.volume;

You need to import the MediaPlayer framework.

aturan23
  • 4,798
  • 4
  • 28
  • 52
borked
  • 1,550
  • 1
  • 11
  • 10
12

For Swift 2:

let volume = AVAudioSession.sharedInstance().outputVolume   
print("Output volume: \(volume)")
Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
Dasoga
  • 5,489
  • 4
  • 33
  • 40
12

This works fine:

Float32 volume;
UInt32 dataSize = sizeof(Float32);

AudioSessionGetProperty (
                     kAudioSessionProperty_CurrentHardwareOutputVolume,
                     &dataSize,
                     &volume
                     );
ziguli
  • 161
  • 1
  • 5
5

You can use the default system's volume View and add to wherever you need it. In my case I required it in my own music player. It's easy and hassle free. Just add the view, and everything is done. This is explained in Apple's MPVolume Class Reference.

mpVolumeViewParentView.backgroundColor = [UIColor clearColor];
MPVolumeView *myVolumeView =
[[MPVolumeView alloc] initWithFrame: mpVolumeViewParentView.bounds];
[mpVolumeViewParentView addSubview: myVolumeView];
[myVolumeView release];
Suraj Pathak
  • 910
  • 8
  • 9
2

I have prepared a class with static methods in order to deal with the volume of ios devices. Let me share with you :)

import AVFoundation
class HeadPhoneDetectHelper {
class func isHeadPhoneConnected() -> Bool
{
    do{
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setActive(true)
        let currentRoute = audioSession.currentRoute
        let headPhonePortDescriptionArray = currentRoute.outputs.filter{$0.portType == AVAudioSessionPortHeadphones}
        let isHeadPhoneConnected = headPhonePortDescriptionArray.count != 0
        return isHeadPhoneConnected
    }catch{
        print("Error while checking head phone connection : \(error)")
    }
    return false
}

class func isVolumeLevelAppropriate() -> Bool
{
    let minimumVolumeLevelToAccept = 100
    let currentVolumeLevel = HeadPhoneDetectHelper.getVolumeLevelAsPercentage()
    let isVolumeLevelAppropriate = currentVolumeLevel >= minimumVolumeLevelToAccept
    return isVolumeLevelAppropriate
}

class func getVolumeLevelAsPercentage() -> Int
{
    do{
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setActive(true)
        let audioVolume =  audioSession.outputVolume
        let audioVolumePercentage = audioVolume * 100
        return Int(audioVolumePercentage)
    }catch{
        print("Error while getting volume level \(error)")
    }
    return 0
}
}
Suat KARAKUSOGLU
  • 622
  • 6
  • 14
1

Swift 2.2, make sure to import MediaPlayer

private func setupVolumeListener()
{
    let frameView:CGRect = CGRectMake(0, 0, 0, 0)
    let volumeView = MPVolumeView(frame: frameView)
    //self.window?.addSubview(volumeView) //use in app delegate
   self.view.addSubview(volumeView)  //use in a view controller


    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(volumeChanged(_:)), name: "AVSystemController_SystemVolumeDidChangeNotification", object: nil)
}//eom



func volumeChanged(notification:NSNotification)
{
    let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"]
    let category = notification.userInfo!["AVSystemController_AudioCategoryNotificationParameter"]
    let reason = notification.userInfo!["AVSystemController_AudioVolumeChangeReasonNotificationParameter"]

    print("volume:      \(volume!)")
    print("category:    \(category!)")
    print("reason:      \(reason!)")
    print("\n")
}//eom
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
LuAndre
  • 1,114
  • 12
  • 23