Tuesday, January 28, 2014

Automated Volume Reset in Linux Mint/Ubuntu

I've been watching course videos lately, which requires me to crank up the volume on my speakers of my Linux Mint PC (using the volume applet in the bottom panel of the display). Being absent-minded (a job requirement when I was a professor), I often forget to reset the volume after watching a video. I'll suspend or hibernate the machine, go off to do something else, come back and resume/thaw, and at some point get blasted out of my chair by an unexpectedly loud system sound. Today I decided it was time to fix this by automatically resetting the volume any time I resume from suspend or "thaw" from hibernation.

I've previously described how to create a script to reset the volume. It turns out that running it at resume/thaw is a bit tricky. There are a number of forum posts on how to run a script at resume/thaw, but the standard solution did not work in this case. I believe the problem was that PulseAudio (the audio system) was running in my user session, whereas the script (being run as the root user) was looking for it in the root user's session and not finding it. The solution involved both baking in a short delay (to ensure that PulseAudio had restarted before trying to control it) and running the volume reset script as me, rather than as root. Adding to the confusion: the usual way to run as someone else, in this case

sudo -u paul ..., did not work (and I'm not sure why, but I'm pretty sure it's tied to whose environment is in use).

Cutting to the chase scene, here is the solution. The script to reset the volume (see the previous post) is /home/paul/Scripts/resetVolume.sh. I created a wakeup script by doing the following in a terminal:

  cd /etc/pm/sleep.d
  sudo touch 00_reset-volume.sh
  sudo chmod +x 00_reset-volume.sh
  sudo gedit 00_reset-volume.sh

There is nothing sacred about the name (00_reset-volume.sh) I used, but the "00" prefix should help ensure that it runs late in the resume sequence (giving more time for my user session to be reloaded, including the PulseAudio daemon).

The contents of 00_reset-volume.sh are as follows:

#!/bin/bash
case "$1" in
  thaw|resume)
    sleep 10 && su -c - paul /home/paul/Scripts/resetVolume.sh
      # wait 10 sec. for PulseAudio to restart
    ;;
  *)
    ;;
esac
exit $?

The 10 second delay before running my volume reset script may not be necessary, but it works, and if it ain't broke, don't fix it. su -c - paul ... runs the script as me rather than as root, apparently using my environment.

No comments:

Post a Comment

Due to intermittent spamming, comments are being moderated. If this is your first time commenting on the blog, please read the Ground Rules for Comments. In particular, if you want to ask an operations research-related question not relevant to this post, consider asking it on Operations Research Stack Exchange.