20 Oct 2009

Smooth volume change in KDE

Of late, I am annoyed by my ThinkPad laptop's volume controls increasing and decreasing volume in steps of 19 (so practically I get only 5 different volume levels).  Today I decided to write a shell script to control volume, rather using the volume buttons on the laptop.  Since I use KDE, making the script talk to KMix using DCOP would be easy and portable (as in, the script will work on any machine running KDE).

KMix's DCOP interface is documented in its manual.  Here is the shell script in its entirety.  It's also available as a downloadable file to save you some typing.

#!/bin/bash
#
# Adjusts speaker volume in KDE.  Does so by sending DCOP commands to KMix.

set -e

function get_volume {
    dcop kmix Mixer0 masterVolume
}

function set_volume {
    dcop kmix Mixer0 setMasterVolume "$1"
}

if [[ "$1" == "" ]]; then
    get_volume
    exit 0
fi

old_volume=$(get_volume)

operator="$1"
shift

case "$operator" in
+)
    set_volume $(expr $(get_volume) + 5)
    ;;
-)
    set_volume $(expr $(get_volume) - 3)
    ;;
*)
    echo >&2 Unrecognized operator "$operator".  Use + to increase and - to decrease volume.
    exit 1
esac

I have saved this file with the name speaker-volume.  When this script is run without any arguments, it prints the current volume level.  When passed "+" as the argument it increases the volume by a small amount, and decreases it when "-" is passed as the argument.

$ ./speaker-volume
58
$ ./speaker-volume +
$ ./speaker-volume
61
$ ./speaker-volume -
$ ./speaker-volume
57

(You may notice that the increase and decrease in the volume is not accurate; I don't know why it is so.  +5 and -3 work reasonably well on my T60p laptop running Kubuntu Hardy.  You may have to tweak these numbers to suit your computer/taste.)

Tip: To make it easy to adjust volume, you can define global shortcut keys as described in my post about adjusting screen brightness.