Changing PulseAudio Outputs Programmatically

By Eric Lathrop on

I got a neat desk-mounted macro pad called the Pikatea. I wanted one of the buttons to cycle my computer's audio output between my headphones and speakers. I found that you can use pactl to inspect PulseAudio settings, and change them. Below is a bash script I wrote to cycle output (i.e. "sinks" in PulseAudio terminology). You can run it multiple times, and it'll pick the next output after the current one.

set -e

default_sink=$(pactl info | grep "Default Sink:" | cut '-d ' -f3)
sinks=$(pactl list short sinks | cut -f2)

# for wrap-around

next_sink=$(echo "$sinks" | awk "/$default_sink/{getline x;print x;exit;}")

pactl set-default-sink "$next_sink"
pactl list short sink-inputs | \
  cut -f1 | \
  xargs -I{} pactl move-sink-input {} "$next_sink"