Last active
November 12, 2019 16:04
-
-
Save devilholk/dbfb1afe34ed01139b2cea0537b38f70 to your computer and use it in GitHub Desktop.
Get volumes from pulseaudio using pactl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires python 3.6 or up (tested on 3.7.4 | |
import subprocess, os, sys, re | |
from collections import defaultdict | |
volume_pattern = re.compile(r'^\s*volume:\s+(.*)', re.I) | |
sink_id_pattern = re.compile(r'^\s*sink\s+#(.*)', re.I) | |
description_pattern = re.compile(r'^\s*description:\s+(.*)', re.I) | |
volume_entry_pattern = re.compile(r'(^|\s+)(?P<name>.*?):\s+(?P<volume_raw>.*?)\s*/\s*(?P<volume_percent>.*?)\%\s*/\s*(?P<volume_db>.*?)\s+db', re.I) | |
def run_command(*cmd): | |
mod_env = dict(**os.environ) | |
mod_env['LANG'] = 'C' | |
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,env=mod_env) | |
raw_stdout, dummy = p.communicate() | |
stdout = raw_stdout.decode(sys.getdefaultencoding()) | |
return stdout | |
def parse_volume(line): | |
return [match.groupdict() for match in volume_entry_pattern.finditer(line)] | |
def get_volumes(): | |
result = defaultdict(dict) | |
current_sink_id = None | |
data = run_command('pactl', 'list', 'sinks') | |
try: | |
for line in data.split('\n'): | |
v_match = volume_pattern.match(line) | |
s_match = sink_id_pattern.match(line) | |
d_match = description_pattern.match(line) | |
if s_match: | |
current_sink_id = int(s_match.group(1)) | |
if v_match: | |
assert current_sink_id != None, 'Found volume before a current sink id!' | |
result[current_sink_id]['volume'] = parse_volume(v_match.group(1)) | |
if d_match: | |
assert current_sink_id != None, 'Found description before a current sink id!' | |
result[current_sink_id]['description'] = d_match.group(1) | |
except AssertionError: | |
print(data, file=sys.stderr) | |
raise | |
return result | |
current_volumes = get_volumes() | |
for sink, data in current_volumes.items(): | |
print(f'Sink #{sink} ({data["description"]})') | |
for entry in data['volume']: | |
print(f'\t{entry}') | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment