How do I get the system output volume in python?
I’m working on a project where I need to get the current system audio output level in Python. Basically, I want to know how much sound the speakers are currently emitting when using Python on a Linux system. I don’t need to know the exact volume of the speakers, I’m looking for relative volume. I haven’t found any good resources online.
Solution
tl; dr – Get an alternative answer to discrete system output volume on macOS.
After seeing your question and learning that I can’t build pyalsaaudio
on macOS, I wanted to provide an additional answer to how to do it specifically on macOS because it’s not abstracted in a cross-platform way.
(I know this won’t help with your immediate use case, but I have a hunch that I’m not the only Mac user interested in this issue, interested in a solution that we can run as well.) )
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 the call in a Python function to parse the 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 with different 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