Skip to content

Instantly share code, notes, and snippets.

@slonkazoid
Forked from OndraZizka/switchHeadphones.sh
Last active April 17, 2021 18:28
Show Gist options
  • Save slonkazoid/bbea27c02c6bee6ecec0b8dc917997fd to your computer and use it in GitHub Desktop.
Save slonkazoid/bbea27c02c6bee6ecec0b8dc917997fd 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)
#!/usr/bin/env bash
ID="74_5C_4B_63_EF_A2" # check 'pacmd list-sinks | grep bluez'
#### Restart Bluetooth
if [ "$1" == "resetBT" ] ; then
sudo rfkill block bluetooth && sleep 0.1 && sudo rfkill unblock bluetooth;
exit;
fi;
#### Toggle listen/speak
if [ "$1" == "" -o "$1" == "toggle" ] ; then
if pacmd list-sinks | grep "bluez_sink.$ID.a2dp_sink" >/dev/null ; then
echo "Currently in A2DP sink mode (listen), switching to Headset Unit mode (speak)"
$0 speak
exit $?; # inherit error code
elif pacmd list-sinks | grep "bluez_sink.$ID.headset_head_unit" >/dev/null; then
echo "Currently in Headset Unit mode (speak), switching to A2DP sink mode (listen)"
$0 listen
exit $?;
fi
exit 1
fi
# Change to A2DP sink
if [ "$1" == "listen" ] ; then
# Set output device to our device
echo "Switching audio output to headset";
pacmd set-default-sink "bluez_sink.$ID.headset_head_unit"
# Change profile to a2dp_sink
echo "Switching audio profile to A2DP sink (listen)";
pacmd set-card-profile bluez_card.$ID a2dp_sink
exit $?
fi;
# Input
if [ "$1" == "speak" ] ; then
# Change profile to headset_head_unit
echo "Switching audio profile to Headset Unit (speak)"
pacmd set-card-profile bluez_card.$ID headset_head_unit
# Set input device to our device
echo "Switching audio input to headset";
pacmd set-default-source "bluez_source.$ID.headset_head_unit";
exit $?
fi;
#### 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
## Made by
#### https://github.com/OndraZizka
## Edited by
#### https://github.com/uAliFurkanY
#### https://gitlab.com/alifurkany
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment