How can I choose the audio output device using the terminal?

I have a digital headphone set and an analog pair of speakers. Is there a way for me to switch between them in the terminal in Ubuntu? I ask that because I would like to create a keyboard shortcut for this switch to make it simpler than having the tedious task of going to the audio settings using the mouse.


Solution 1:

Sure, you could use the "pactl" and "pacmd" command.

An example for a pair of external USB speaker + internal speakers, with music playing.

$ pactl list sinks short | awk -F '\t' '{print $1,$2,$5}' # Print available outputs
0 alsa_output.pci-0000_00_1b.0.analog-stereo RUNNING
1 alsa_output.usb-Logitech_Logitech_Z-5_Speakers-00-Speakers.analog-stereo SUSPENDED

The first one with index 0 is the internal speak, music is running on this sink. Another one with index 1 is the external USB speaker.

$ pactl stat | grep Sink  # Show the current output device (it's the internal speaker)
Default Sink: alsa_output.pci-0000_00_1b.0.analog-stereo
$ pacmd set-default-sink 1 # Make the external USB speaker as desired output device.

If you're not palying anything during the switch, you could stop here.

(Note, to make sure it really works, it would be better to do this with something playing, and move the stream as follows.)

If you're playing something you will notice that the music still running on the old device, you have to move it to the desired device:

$ pactl list sink-inputs | grep 'Input' # Get the stream ID
Sink Input #23
$ pacmd move-sink-input 23 1 # Move it to the USB speaker

Voilà! You could compose a script base on these.

Reference: How to change pulseaudio sink with “pacmd set-default-sink” during playback?