How do I access the current volume level of a Mac from the Cocoa API?
For example: when I’m using Spotify.app on OS X 10.7 and a sound advertisement comes up, and I turn down my Mac’s volume, the app will pause the ad until I turn it back up to an average level. I find this incredibly obnoxious and a violation of user privacy, but somehow Spotify has found a way to do this.
Is there any way I can do this with Cocoa? I’m making an app where it might come in useful to warn the user if the volume is low.
There are two options available. The first step is to determine what device you’d like and get its ID. Assuming the default output device, the code will look something like:
Next, you can use the
kAudioHardwareServiceDeviceProperty_VirtualMasterVolumeproperty to get the device’s virtual master volume:Alternatively, you can use
kAudioDevicePropertyVolumeScalarto get the volume for a specific channel:The difference between the two is explained in Apple’s docs:
So it can be tricky to define exactly what a device’s volume is, especially for multichannel devices with non-standard channel maps.