Skip to content

Instantly share code, notes, and snippets.

@elundmark
Last active April 26, 2021 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elundmark/4c3cedcf8a075b67b8b06f943ee1938e to your computer and use it in GitHub Desktop.
Save elundmark/4c3cedcf8a075b67b8b06f943ee1938e to your computer and use it in GitHub Desktop.
Monitor audio-cable In or Out
#!/usr/bin/env bash
# NOTE! This script checks card 1, yours may be different
declare -i CARD=1
if amixer -c "$CARD" contents | grep -A2 'Headphone' | grep -q 'values=on'
then
mkdir /tmp/.audio-cable-connected &>/dev/null
fi
get_unplugged_cable_count(){
grep -cP '^\s*Pin-ctls:.+OUT' "/proc/asound/card${CARD}/codec#0"
# > 2 # connected
# > 4 # unplugged
return $?
}
declare -a log_cmd=(echo)
declare -i OUT_NUM=-1 TMP_NUM=0
OUT_NUM=$(get_unplugged_cable_count)
while read -r; do
if grep -qP "^Event '(change|new)' " <<< "$REPLY"; then
TMP_NUM=$(get_unplugged_cable_count)
if [[ "$OUT_NUM" -lt "$TMP_NUM" ]] ; then # cable disconnected
# vol force-unmute
# vol set 0
"${log_cmd[@]}" "Cable(s) unplugged (change: ${OUT_NUM} -> ${TMP_NUM})" 1>&2
OUT_NUM=$((TMP_NUM+0))
rmdir /tmp/.audio-cable-connected &>/dev/null
elif [[ "$OUT_NUM" -gt "$TMP_NUM" ]] ; then # new cable connected
# vol force-unmute
# vol set 24%
"${log_cmd[@]}" "Cable(s) connected (change: ${OUT_NUM} -> ${TMP_NUM})" 1>&2
OUT_NUM=$((TMP_NUM+0))
mkdir /tmp/.audio-cable-connected &>/dev/null
fi
fi
done < <(echo && stdbuf -oL pactl subscribe)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment