Change Volume From a Bash Script

If you use ALSA for sound on your system the functions contained in the script presented here can be used to get and set the volume on your system. You might use this if you had a monitoring script running and wanted to raise the volume when you signal an alarm and then lower it again to the previous volume.

The get function uses amixer to output the information for the simple mixer control "Master" and then uses grep and cut to get the correct value from the output.

The set function also uses amixer to set the volume. It uses the "cset" option to amixer.

The script follows:

#!/bin/bash
#

#####################################################################
# Get current volume.
function get_volume()
{
    mixer=$(amixer get Master | grep 'Front Left:')
    echo $mixer | cut -d ' ' -f 4
}


#####################################################################
# Set volume.
function set_volume()
{
    amixer cset iface=MIXER,name="Master Playback Volume" $1 >/dev/null
}

if [[ $(basename $0 .sh) == 'sound' ]]; then
    sound_file=~/Documents/sounds/notify.wav
    if [[ "$1" ]]; then sound_file="$1"; fi

    ovol=$(get_volume)
    echo "Current volume: $ovol"
    aplay $sound_file
    sleep 2

    vol=40
    echo "Playing at: $vol"
    set_volume $vol
    aplay $sound_file
    sleep 2

    echo "Again at: $ovol"
    set_volume $ovol
    aplay $sound_file
fi
    

# vim: tabstop=4: shiftwidth=4: noexpandtab:
# kate: tab-width 4; indent-width 4; replace-tabs false;

If you save the script as sound.sh and run it directly passing the name of a sound file it will play the file at the current volume, then it raises the volume and plays it again, and finally it restores the volume and plays it one last time. If you open your mixer controls before running the script you should see the master volume control move as the script changes the volume. You can adjust the value in the line vol=40 to get the volume you want.

Mitch Frazier is an embedded systems programmer at Emerson Electric Co. Mitch has been a contributor to and a friend of Linux Journal since the early 2000s.

Load Disqus comments