Switching audio bluetooth profiles with a script
I wanted to be able to switch between “listening to music” and “using the headphone’s microphone” easily. i3blocks allows me to write scripts emit a status line, and can accept “clicks” in the form of environment variables to respond. I wrote one that, using the pulseaudio CLI:
- Checks how many audio bluetooth devices are connected
- If there are none / more than one, prints that and exits
- If there was a mouse left click, choose the “other profile” and apply it
- Print the current profile
It’s pretty short and sweet, so I thought I’d share it
The Script
#!/bin/bash
set -Eeuo pipefail
INDEXES="$(pacmd list-cards | (grep 'name: <bluez_card.' -B2 || true) | perl -ne 'print $1,$/ if /index: (\d+)/')"
INDEX_COUNT="$(echo "$INDEXES" | wc -l)"
if [[ "$INDEX_COUNT" > 1 ]]; then
echo "MULTIPLE"
exit
elif [[ "$INDEX_COUNT" < 1 || "$INDEXES" == "" ]]; then
echo "NONE"
exit
fi
# Only one
INDEX="$INDEXES"
get_profile() {
pacmd list-cards | grep "index: ${INDEX}" -A22 | perl -ne 'print $1,$/ if /active profile: <(.+)>/'
}
# left click
if [[ "${BLOCK_BUTTON:-0}" == 1 ]]; then
if [[ "$(get_profile)" == "a2dp_sink" ]]; then
NEXT_PROFILE="handsfree_head_unit"
else
NEXT_PROFILE="a2dp_sink"
fi
pacmd set-card-profile "$INDEX" "$NEXT_PROFILE"
fi
get_profile