How to mute sound when xscreensaver locks screen

audiopulseaudioxscreensaver

The goal is to mute sound whenever screen lock happens.

Ideally restore sound after unlocking as well.

Sound system is Pulseaudio.

Best Answer

Launch this script (or setup autostart of this script on login):

#!/bin/bash -euET
{
set -o pipefail

export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/user/$(id -u)/bus}"
export DISPLAY="${DISPLAY:-:0}"

xscreensaver-command -watch | while read -r line ; do
    echo "handling event: $line"

    if [[ $line = LOCK* ]]; then
      volume=$(pamixer --get-volume)
      echo "current volume is $volume"
      pamixer --set-volume 0
    fi

    if [[ $line = UNBLANK* ]]; then
      echo "setting volume to $volume"
      pamixer --set-volume "$volume"
    fi
done

exit
}

Explanation: the "daemon" part of this script xscreensaver-command -watch will hang and wait for any events from xscreensaver. Whenever "LOCK" or "UNBLANK" event occurs, the sound volume will be zeroed and restored respectively.

Related Question