Skip to content

Instantly share code, notes, and snippets.

@natenho
Forked from OndraZizka/switchHeadphones.sh
Last active July 22, 2022 08:11
Show Gist options
  • Save natenho/a9d76a3b8230844f38b8236ed3fc745a to your computer and use it in GitHub Desktop.
Save natenho/a9d76a3b8230844f38b8236ed3fc745a to your computer and use it in GitHub Desktop.
Bluetooth headset - switch between quality sound + no mic (A2DP) and crappy sound and mic (HSP/HFP)
#!/bin/bash
CARD=$(pactl list | grep bluez_card | awk '{print $NF}')
BLUETOOTH_DEVICE=$(pacmd list-sinks | grep -o '<bluez_sink[^>]*' | cut -d\< -f2)
PROFILE_A2DP="a2dp_sink"
PROFILE_HEADSET_UNIT="headset_head_unit"
if [ "${1}" == "" -o "${1}" == "toggle" ] ; then
if $(pacmd list-sinks | grep -o "<bluez_sink\..*\.$PROFILE_A2DP>" &> /dev/null) ; then
echo "$PROFILE_A2DP->$PROFILE_HEADSET_UNIT"
${0} speak;
else
echo "$PROFILE_HEADSET_UNIT->$PROFILE_A2DP"
${0} listen;
fi
fi
if [ "${1}" == "listen" ] ; then
pactl set-card-profile "$CARD" "$PROFILE_A2DP" || echo "Problem setting profile"; exit 3
pacmd set-default-sink "$BLUETOOTH_DEVICE" || echo "Problem setting default sink"; exit 4
exit;
fi;
if [ "${1}" == "speak" ] ; then
pactl set-card-profile "$CARD" "$PROFILE_HEADSET_UNIT" || echo "Problem setting profile"; exit 3
pacmd set-default-sink "$BLUETOOTH_DEVICE" || echo "Problem setting default sink"; exit 4
fi;
#### Usage:
# Associate this script with a convenient hotkey in your system running, it will automatically toggle between A2DP and HSP bluetooth profile
#### Resources:
## Why this is needed
# https://jimshaver.net/2015/03/31/going-a2dp-only-on-linux/
## My original question
# https://askubuntu.com/questions/1004712/audio-profile-changes-automatically-to-hsp-bad-quality-when-i-change-input-to/1009156#1009156
## Script to monitor plugged earphones and switch when unplugged (Ubuntu does that, but nice script):
# https://github.com/freundTech/linux-helper-scripts/blob/master/padevswitch/padevswitch
## Linux Mint Forum script
# https://forums.linuxmint.com/viewtopic.php?t=295859
@schnipseljagd
Copy link

works great for me. The only this I had to change is headset_head_unit to handsfree_head_unit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment