I'm working on a project where I need to get the current system audio output level within Python. Basically, I want to know how loud the current sound coming out of the speakers are using Python on a Linux system. I don't need to know the exact volume level of the speakers, the relative volume is what I'm looking for. I haven't found any good resources online for this.
After seeing your question and learning that I can't build pyalsaaudio on macOS, I wanted to provide an additional answer for how this could be done on macOS specifically since it's not abstracted in a cross-platform way.
(I know this won't be helpful to your immediate use case, but I have a hunch I'm not the only Mac user that will stumble by this question interested in a solution that we can run too.)
On macOS, you can get the output volume by running a little AppleScript:
$ osascript -e 'get volume settings'
output volume:13, input volume:50, alert volume:17, output muted:false
I wrapped that call in a Python function to parse volume + mute state into a simple 0–100 range:
import re
import subprocess
def get_speaker_output_volume():
"""
Get the current speaker output volume from 0 to 100.
Note that the speakers can have a non-zero volume but be muted, in which
case we return 0 for simplicity.
Note: Only runs on macOS.
"""
cmd = "osascript -e 'get volume settings'"
process = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
output = process.stdout.strip().decode('ascii')
pattern = re.compile(r"output volume:(\d+), input volume:(\d+), "
r"alert volume:(\d+), output muted:(true|false)")
volume, _, _, muted = pattern.match(output).groups()
volume = int(volume)
muted = (muted == 'true')
return 0 if muted else volume
For example, on a MacBook Pro at various volume bar settings:
>>> # 2/16 clicks
>>> vol = get_speaker_output_volume()
>>> print(f'Volume: {vol}%')
Volume: 13%
>>> # 2/16 clicks + muted
>>> get_speaker_output_volume()
0
>>> # 16/16 clicks
>>> get_speaker_output_volume()
100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With