Anton Sarukhanov

Full-Stack Developer

Mute speakers when locking your PC

Automatically mute audio output when your computer is locked.

lockmute icon

Are your coworkers/cohabitants tired of hearing notifications and other noises from your unattended computer? Use this script to automatically mute your speakers whenever the machine is locked, and un-mute when you return.

  • Tested with GNOME 3.30 on Debian 10.
  • Mutes when locking, un-mutes when unlocking.
  • Does not un-mute if mute was enabled prior to locking the screen.

How it works🔗

  • Watches org.freedesktop.login1 for LockedHint events via gdbus monitor.
  • Uses amixer (ALSA) to mute/unmute.
#!/bin/bash

# lockmute.sh - Mute sound output while GNOME is locked.

STATE_FILE=~/.lockmute_state
gdbus monitor -y -d org.freedesktop.login1 |
    while read -r DBUS_OUTPUT ; do
        LOCK_STATE=$(echo "$DBUS_OUTPUT" |
                     grep -o "'LockedHint': <\w*>" |
                     awk '{print $2}')
        if [[ "$LOCK_STATE" == "<true>" ]]; then
            AUDIO_STATE=$(amixer get Master |
                          grep -o '\[\(on\|off\)\]')
            if [[ "$AUDIO_STATE" == *"[off]"* ]]; then
                echo "WAS_MUTED" > "$STATE_FILE"
            else
                echo "WAS_NOT_MUTED" > "$STATE_FILE"
            fi
            amixer set Master mute > /dev/null
        elif [[ "$LOCK_STATE" == "<false>" ]]; then
            if [[ "$(cat "$STATE_FILE")" == "WAS_NOT_MUTED" ]]; then
                amixer set Master unmute > /dev/null
            fi
            rm "$STATE_FILE"
        fi
    done

Installation🔗

  1. Save to /usr/local/bin/lockmute.sh.
  2. Make it executable: chmod +x /usr/local/bin/lockmute.sh.

Test it🔗

You can test it by running lockmute.sh in a terminal. Play some music, and lock the screen (Super+L).

Run it automatically🔗

To run this anytime you're logged in, create an autostart entry.

~/.config/autostart/lockmute.desktop🔗

[Desktop Entry]
Name=lockmute
Exec=/usr/local/bin/lockmute.sh
Type=Application
NoDisplay=true
X-GNOME-Autostart-enabled=true