Switching PulseAudio output device
I have my desktop computer connected to a hi-fi and a television screen through HDMI. This means that I'm often switching video and audio outputs from my monitor and speakers on the desk to the TV and vice-versa. Changing video output via xrandr from a shell script is trivial. Convincing PulseAudio daemon to switch audio outputs is a completely different can of worms.
In GNOME you switch the audio output from the user-friendly Sound Preferences window (internally called gnome-volume-control). This requires several clicks of the mouse and doesn't have a command-line interface to it as far as I know. Its effect is instantaneous and even works reliably with applications that are playing audio while switching outputs.
PulseAudio itself comes with two basic command line tools, called pacmd and pactl. Former offers a set-default-sink command, but that doesn't do what you expect from it. It turns out that, at least on my system, PulseAudio daemon keeps persistent settings for each application that ever connected to it. This means that the default sink only gets used for applications that the daemon hasn't seen yet.
Digging through the source code of gnome-volume-control revealed that it walks through the stored persistent settings and modifies them each time you change the sound output device in that dialog window.
So what I did is copy the way gnome-volume-control does it and package it into a simple command-line utility, paswitch.
You can get it here:
$ git clone http://www.tablix.org/~avian/git/paswitch.git
Once you compile it by calling make, the usage is straightforward:
$ paswitch alsa_output.pci-0000_01_00.1.hdmi-stereo
To obtain the name of the sink, you can run pactl:
$ pactl list
...
Sink #0
State: SUSPENDED
Name: alsa_output.pci-0000_01_00.1.hdmi-stereo
...
By the way, this answer offers a different way of doing it. However it requires turning off persistent settings via restore_device=false in PulseAudio configuration.







