Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Created October 30, 2023 20:54
Show Gist options
  • Save markscottwright/351c1c6e43c1d7cd88a6d0ce4702e8ee to your computer and use it in GitHub Desktop.
Save markscottwright/351c1c6e43c1d7cd88a6d0ce4702e8ee to your computer and use it in GitHub Desktop.
How to set the output audio device in modern Ubuntu-derivatives
#! /usr/bin/python3
# Note: use wpctl set-default <number> to use this information
from subprocess import check_output
import os
import re
import sys
'''
pw-cli ls | awk '/^\s*id/{ id=$2; sub(",", "", id) }/\s*node.description/{ name=substr($0, index($0, "=")+2); gsub("\"", "", name) } /\s*media.class.*Audio.Sink/ { print( id " " name ) }'
echo
echo use wpctl set-default NUMBER to use this information
'''
device_to_set = None
if len(sys.argv) > 1:
device_to_set = sys.argv[1]
audio_info = check_output(['pw-cli', 'ls'], text=True).splitlines()
audio_id = None
node_description = None
for l in audio_info:
m = re.match(r"^\s*id\s*([0-9]+),.*$", l)
if m:
audio_id = m.group(1)
if l.strip().lower().startswith('node.description'):
node_description = l.strip().split("=")[1].strip()
if re.search('media.class.*Audio.Sink', l):
if device_to_set is None:
print(audio_id, node_description)
else:
if device_to_set.lower() in node_description.lower():
print(f"setting default output to: {node_description} ({audio_id})")
os.system(f"wpctl set-default {audio_id}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment