Creative Commons

2011-03-18 21:46:50

Adjust Volume From The Terminal

Back when I used FreeBSD, it was a piece of cake to change the volume. I could just run something like:

mixer vol 90

and the volume was set to 90%. Unfortunately that does not work on Linux systems.

Modern Linux systems use Pulse Audio as the sound system and the ALSA utilities still work as well. This is what we'll use to change the volume.

What sucks though is that the ALSA commands aren't intuitive... at all. Quite the opposite. First, we need to query ALSA to get a list of our sound control devices so we know which one on which to change the volume.

amixer controls

We're looking for "Master Playback Volume". On my machine, it happens to have the ID of 3. Now that we know which control to change, we need to know how to specify the volume. Each control has a value associated with it. In the case of the "Master Playback Volume", that value is an integer from 0 to 65536. Yup, instead of making this simple and using 0-100 they decided to use the full value range of an unsigned integer. So, if we wanted to set our volume to 100%, we would run:

amixer cset numid=3 65536

Great, we now know how to set the volume. However, we'd rather have a simpler way to do this. Maybe something that didn't make us do math. Computers are good at math, let's make it do it's job. I wrote a tiny Perl script that takes one input value, 0-100, and correctly sets the "Master Playback Volume".

> cat #!/usr/bin/perl $uservol = $ARGV[0]; $uservol =~ s/\n//; $alsavol = $uservol * 655.36; $intvol = sprintf("%d", $alsavol); $command = "amixer -q cset numid=3 " . $intvol; $command =~ s/\n//; system($command);

So the script is pretty simple. It grabs the first argument, which should be a number from 0-100, multiplies it by 655.36 to get it on the same scale that the amixer command likes, removed any decimal places with the sprintf function, then runs the amixer command.

To make this even easier, I added an alias to my .cshrc so I can invoke it with a single keystroke:

m 50

The alias "m" will invoke, thus setting my volume to 50%. Perfect!


Post a comment!