Switching between builtin speakers and headphones in the command line

In most devices attaching the headphones into the device would immediately set the headphones as the audio output device. Same with pulling the headphones out - the output device would be set to the builtin speakers.

In Librem14, as far as I can tell, one has to switch output devices manually in Settings → Sound → Output → Output Device.

I personally find this default behavior of Librem14 to be great, but it would be even better if I could attach it to a keybinding, and for that I need a command to run in a shell script.

What’s the command that switches between audio devices?

2 Likes

The following commands will set the output device to headphones and speakers:

pactl set-sink-port alsa_output.pci-0000_00_1f.3.analog-stereo analog-output-headphones
pactl set-sink-port alsa_output.pci-0000_00_1f.3.analog-stereo analog-output-speaker

if these exact names do not fit your case, you can use tab-completion to see a list of possibilities.

Here is a dumb looking Python script I wrote:

#!/usr/bin/env python3

from subprocess import Popen, PIPE


def get_current_active_port() -> str:
    pactl_list_sinks = Popen(["pactl", "list", "sinks"], stdout=PIPE)

    output, stderr = pactl_list_sinks.communicate()

    current_active_port = [
        line.split(": ")[1].strip()
        for line in output.decode().split("\n")
        if "Active Port:" in line
    ][0]

    return current_active_port


def main() -> None:
    current_active_port = get_current_active_port()
    print("Current active port:", current_active_port)

    if current_active_port == "analog-output-headphones":
        Popen(
            [
                "pactl",
                "set-sink-port",
                "alsa_output.pci-0000_00_1f.3.analog-stereo",
                "analog-output-speaker",
            ]
        ).wait()
    elif current_active_port == "analog-output-speaker":
        Popen(
            [
                "pactl",
                "set-sink-port",
                "alsa_output.pci-0000_00_1f.3.analog-stereo",
                "analog-output-headphones",
            ]
        ).wait()

    current_active_port = get_current_active_port()
    print("New current active port:", current_active_port)


if __name__ == "__main__":
    main()
2 Likes