CLI to switch audio outputs on Linux

I typically have headphones permanently connected to my desktop computer but still find the need to quickly switch the audio to the desktop speakers. I’d prefer to avoid plugging/unplugging my headphones so came up with this approach.

This uses the Pulse Audio controller command: pactl

First identify your available audio outputs:

1
2
3
4
$ pactl list short | grep alsa_output | grep -v monitor
0 alsa_output.usb-Logitech_G635_Gaming_Headset_00000000-00.iec958-stereo module-alsa-card.c s16le 2ch 44100Hz SUSPENDED
1 alsa_output.pci-0000_08_00.1.hdmi-stereo module-alsa-card.c s16le 2ch 44100Hz SUSPENDED
2 alsa_output.pci-0000_0a_00.4.analog-stereo module-alsa-card.c s16le 2ch 44100Hz SUSPENDED

Then create some scripts to set the chosen output / sink.

/usr/local/bin/switch_2_headphones.sh

1
2
3
#!/bin/bash

pactl set-default-sink alsa_output.usb-Logitech_G635_Gaming_Headset_00000000-00.iec958-stereo && espeak "headphones"

/usr/local/bin/switch_2_speakers.sh

1
2
3
#!/bin/bash

pactl set-default-sink alsa_output.pci-0000_0a_00.4.analog-stereo && espeak -g 0 "spee kurz"

Then setup some keyboard shortcuts to run the scripts. I chose ALT-SHIFT-S and ALT-SHIFT-H for speakers and headphones, respectively.

upload successful

*UPDATE NOV 2022: * After upgrading to Mint 21 there needs to be an additional change to /etc/pulse/default.pa for the CLI sink changes to work.

Change line load-module module-stream-restore to load-module module-stream-restore restore_device=false

Then restart pulseaudio via pulseaudio --kill then pulseaudio --start.