A Weird Imagination

Volume via shell

Posted in

The problem#

Sometimes a GUI is not the best way to control a computer's volume. Usually if you care about the volume of your computer, you're probably nearby but perhaps would rather be using a remote or other shortcut way of changing the volume. The specific use case that prompted this blog post was binding the volume up and volume down keys on my keyboard to the global volume control (as opposed to separately binding them in each application).

PulseAudio command line tools#

PulseAudio can be controlled using the pactl and pacmd command line tools.

The pactl subcommand for controlling the volume is set-sink-volume, which takes as its first argument a card name or index.

Choosing a card#

In order to get the name of your sound card, use the list subcommand:

$ pactl list cards | grep -F 'Name:
description'
        Name: alsa_card.pci-0000_01_00.1
                device.description = "HDA NVidia"
        Name: alsa_card.pci-0000_00_1b.0
                device.description = "Built-in Audio"

The output for my computer shows both the built-in audio card that I care about and the HDMI audio output for my NVidia graphics card. The full output of the pactl command provides a lot more information to clarify which card is which if the description is not enough information.

Setting the volume#

The second argument to set-sink-volume is the new volume. Since these commands are for volume down/up controls, we want to set the volume relative to the current volume. Luckily, pactl accepts volume specifications preceded by a - or + to indicate a relative volume:

$ pactl -- set-sink-volume "alsa_output.pci-0000_00_1b.0.analog-stereo"\
    "-2dB"  # volume down
$ pactl -- set-sink-volume "alsa_output.pci-0000_00_1b.0.analog-stereo"\
    "+2dB"  # volume up

Note the use of -- so that -2dB is not interpreted as an option. You can also adjust by percentages instead of decibels.

ALSA command line tools#

The equivalent for ALSA is to use amixer:

$ amixer -c 0 set Master 2dB-  # volume down
$ amixer -c 0 set Master 2dB+  # volume up

Additionally, there's a ncurses graphical mixer for ALSA alsamixer which provides an experience more like what you would expect from a GUI mixer but runs on the command line so it could, for example, be accessed over SSH.

As it's a common mistake I make when using alsamixer, note that in alsamixer, q not only doesn't quit, it instead increases the volume on only the left channel (z decreases it). To quit, hit esc.

Comments

Have something to add? Post a comment by sending an email to comments@aweirdimagination.net. You may use Markdown for formatting.

There are no comments yet.