Get System Volume iOS
Asked Answered
Z

8

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?

Zulemazullo answered 31/8, 2011 at 9:23 Comment(0)
C
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));
Caress answered 6/5, 2013 at 19:20 Comment(4)
I use in iOS 11 in today extension - sometimes it doesn't workDelila
#24872909 -try playing audio then checking. Had same proble, worked for me.Funeral
Make sure to also do AVAudioSession.sharedInstance().setActive(true) first or this value will not update when the volume is changedTingaling
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.Winnipegosis
C
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

Cabrales answered 8/5, 2017 at 14:32 Comment(1)
Can you share why setActive(true) is important?Pistole
H
13

Try this:

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

You need to import the MediaPlayer framework.

Happening answered 19/9, 2011 at 17:41 Comment(1)
It is deprecated, use [[AVAudioSession sharedInstance] outputVolume] instead.Sandrasandro
S
12

This works fine:

Float32 volume;
UInt32 dataSize = sizeof(Float32);

AudioSessionGetProperty (
                     kAudioSessionProperty_CurrentHardwareOutputVolume,
                     &dataSize,
                     &volume
                     );
Schnook answered 17/10, 2011 at 9:1 Comment(2)
Even better in my case! Now I can ditch the MediaPlayer Framework.Zulemazullo
This is deprecated in iOS 7 - does anybody know the new way?Loos
C
12

For Swift 2:

let volume = AVAudioSession.sharedInstance().outputVolume   
print("Output volume: \(volume)")
Cinder answered 17/3, 2016 at 0:35 Comment(1)
We also need audioSession.setActive(true)Riddick
C
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];
Chambless answered 23/11, 2012 at 2:26 Comment(2)
The question was not how to provide the user with a way of changing the volume, but how to detect if the volume was high enough. How does this answer help?Zulemazullo
True not particularly relevant to the question but still useful within the greater context of how to adjust system volume.Esquire
C
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
}
}
Corwun answered 3/2, 2016 at 14:25 Comment(0)
J
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
Judgment answered 27/5, 2016 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.