I solved
This is how I achieved this needs:
#!/bin/bash
SINKID=$(pacmd list-sinks | sed -n -e '3{p;q}' | awk '{ print $2 }' | tr -d '><')
ACTIVESINK=$(pacmd list-sinks | grep 'active port' | awk '{ print $3 }' | tr -d '><')
if [ "$ACTIVESINK" == "analog-output-headphones" ]; then
pacmd set-sink-port $SINKID analog-output-speaker
fi
if [ "$ACTIVESINK" == "analog-output-speaker" ]; then
pacmd set-sink-port $SINKID analog-output-headphones
fi
exit 0
If is active the output speaker, this script switch it to headphones; if the output is set to headphones, it switch back to speaker.
Let me explain why I needed this.
Obviously, when I plug in the headphones, the audio output is automatically switched to headphones.
So, why I need to do it manually?
Well: I installed SoundWire app on one Android Phone, and on Manjaro, its counterpart: SoundWire Server, so I can send any audio which I’m listen on Linux, to the Android phone.
But there is an annoying thing: when I transmit the audio to the phone, at the same time is reproduced on the laptop’s speakers. Nope: is not enough muting the audio, because is also muted on Android; the only way to stop the audio output on laptop when is reproduced on the phone, was to plug in the headphones, but maybe I need them fom something else.
So I noticed that if in Pavucontrol I set the audio output to headphones (also if they are not present) I achieved the same result.
Now I launch SoundWire Server on Manjaro, using the following script:
#!/bin/bash
SINKID=$(pacmd list-sinks | sed -n -e '3{p;q}' | awk '{ print $2 }' | tr -d '><')
pacmd set-sink-port $SINKID analog-output-headphones
SoundWireServer &
echo $! > /tmp/sndwire
pid=$(cat /tmp/sndwire)
### Wait for process termination ###
tail --pid=$pid -f /dev/null
### process is ended: run the post actions ###
pacmd set-sink-port $SINKID analog-output-speaker
As I start SoundWire Server the output is switched to headphones, and as I quit it, the audio output is restored to laptop’s speakers