Sunday, August 07, 2022

Changing Bluetooth headset profiles on Linux

I run Linux Mint XFCE on my HP T630 thin client, and when I pair it with a Bluetooth headset, Pulseaudio always defaults to A2DP profile. This does not allow the use of the headset's microphone, which means I have to manually switch to HSP profile each time I want to use the microphone.

So I started looking around for a way to toggle between A2DP and HSP profiles. After reading this and this, I came up with this switch, which I bind to my keyboard as Ctrl + Shift + F10.

#!/bin/bash

a2dpsink=`pactl list | grep Active | grep a2dp`
cardname=$(pactl list | grep bluez_card | awk '{print $NF}')

if [ -n "$a2dpsink" ]; then
    echo "Switching $card to headset..."
    pactl set-card-profile $cardname headset_head_unit
    devicename=$(pacmd list-sinks | grep -o '<bluez_sink[^>]*' | cut -d\< -f2)
    pacmd set-default-sink "$devicename"
    echo "...done"
else
    echo "Switching $card to a2dp..."
    pactl set-card-profile $cardname a2dp_sink
    devicename=$(pacmd list-sinks | grep -o '<bluez_sink[^>]*' | cut -d\< -f2)
    pacmd set-default-sink "$devicename"
    echo "...done"
fi


And... I then found out a simpler method. Newer versions of Pulseaudio actually allows automatic switching between A2DP and HSP. Basically, the default is A2DP, and when the microphone is needed by an application, Pulseaudio will automatically switch to HSP. This feature, however, requires auto_switch=2 to be placed in /etc/pulse/default.pa file. In this file, find the line
load-module module-bluetooth-policy
and change it to
load-module module-bluetooth-policy auto_switch=2
and tada! Thanks to this post!

Note: It seems that using auto_switch=2 may interfere with Steam Remote Play, so if you are using Steam Link or the Steam client for Remote Play, the first option of a keyboard binding to a script should work better.

If you have handsfree_head_unit instead of headset_head_unit, you may need to make a change to the /etc/pulse/default.pa file. Find the line
load-module module-bluetooth-discover
and change it to
load-module module-bluetooth-discover enable_msbc=false
or
load-module module-bluetooth-discover enable_msbc=false headset=auto
(try around, see which one works) to get the HFP profile working. Change headset_head_unit in the script to handsfree_head_unit so that it will work.

No comments: