2

I am running a script that produces audio output, and I want to set different volume levels depending on whether headphones are plugged into my notebook or not.

My script already sets different volume levels, and I know that if something is plugged into audio-out, it are the headphones. It is also certain that the plugged/unplugged state will not change during the run-time of the script. So I really only need to know if something is plugged in or not when the script is started.

I am running Debian testing, and my kernel does not have CONFIG_SND_HDA_INPUT_JACK, but preferably the method would work for all *nix.

hoijui
  • 611
  • 1
  • 6
  • 14
  • Did you check https://unix.stackexchange.com/questions/25776/detecting-headphone-connection-disconnection-in-linux – Stefaan Ghysels Dec 03 '18 at 10:56
  • yes I did. I do not need a signal on unplug/plug event, but the current state, plus I don't have th erequired kernel config set anyway. – hoijui Dec 03 '18 at 12:20

2 Answers2

2

A possibly shorter script fishing into all cards.

#!/bin/sh
# You can put the function below into /etc/profile.d/99-headset.sh
#
has_headset(){
  grep -A4 -ri 'Headphone Playback Switch' /proc/asound/card*/* | \
    grep "Amp-Out vals.*0x00 0x00" -q
}

has_headset

1

This works for me on Debian buster, though you might have to adjust the snd_card_num value. Most likely it should be 0 or 1. Probably the easiest way to find out which value you need, is to try from 0 upwards. For me it is 1.

As mentioned by @dirkt, you may also have to adjust the node_num.

shell script checkHeadphones :

#!/bin/sh
# Check whether the headphones (or speakers) are plugged in or not.
# Usage:
#   checkHeadphones > /dev/null
#   if [ $? -eq 0 ]; then
#     echo "Headphones are connected"
#   else
#     echo "Headphones are not connected"
#   fi

snd_card_num=0
node_num="0x16"
snd_card_file="/proc/asound/card${snd_card_num}/codec#0"

# Run the check
cat "${snd_card_file}" \
    | grep -A 4 'Node $node_num' \
    | grep 'Amp-Out vals:  \[0x00 0x00\]' \
    > /dev/null

exit_state=$?

if [ $exit_state -eq 0 ]; then
    state="connected"
else
    state="disconnected"
fi

echo "$state"
exit $exit_state
hoijui
  • 611
  • 1
  • 6
  • 14
  • 1
    You'll not only have to adjust the `snd_card_num` value, you also have to adjust the `Node` number, because it's different for every sound codec, and it won't work at all for a non-HDA soundcard without codec. But this is a nice solution at the codec level. Other options are to check the ALSA mixer values using `amixer`, or the Pulseaudio profile. – dirkt Dec 11 '18 at 12:39