Skip to content

Instantly share code, notes, and snippets.

@smoser
Last active February 27, 2017 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoser/46bc23907a0f4db00a41088d912386dd to your computer and use it in GitHub Desktop.
Save smoser/46bc23907a0f4db00a41088d912386dd to your computer and use it in GitHub Desktop.
headset-setup : set the bluetooth headset profile to a2dp or headset or off

headset-setup

This is just a small python program that pokes pulseaudio to set the profile of my bluetooth headset to a2dp and also to remind me how to fix it.

setup

venv just creates a virtual env and enters it.

venv create --py3 pulseaudio pip install pulsectl

Usage

headset-setup a2dp

Notes

There are loads of bugs and askubuntu questions and things that mention pulseaudio not able to set up a2dp.

My big aha! moment was realizing if i pushed the 'pause' button on my headset that all of a sudden i could then change the input to a2dp.

#!/usr/bin/env python3
# https://gist.github.com/smoser/46bc23907a0f4db00a41088d912386dd
import argparse
import sys
import os
try:
from pulsectl import Pulse, pulsectl
except ImportError as e:
if os.environ.get('_BT_EXEC', "0") != "0":
# avoid recursion
sys.exit(1)
os.environ['_BT_EXEC'] = "1"
os.execvp('venv', ['venv', 'activate', 'pulseaudio'] + sys.argv)
def main():
smap = {'a2dp': 'a2dp_sink', 'headset': 'headset_head_unit', 'off': 'off'}
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='count', default=0)
parser.add_argument('mode', choices=smap.keys(), default='a2dp')
args = parser.parse_args()
with Pulse('local-smoser-pulse') as pulse:
devs = [d for d in pulse.card_list() if
d.name.startswith('bluez')]
if len(devs) == 0:
sys.stderr.write("No bluetooth devices?\n")
elif len(devs) > 1:
sys.stderr.write("Too many matches: %s\n" % devs)
for d in devs:
sys.stderr.write(
"%s %s\n" % (d.name, d.proplist['device.description']))
if len(devs) != 1:
sys.exit(1)
headset = devs[0]
#for prof in headset.profile_list:
# print("%s: %s" % (prof.name, prof.description))
print("Setting %s [%s] to %s" %
(headset.proplist['device.description'], headset.name,
args.mode))
try:
pulse.card_profile_set(headset, smap[args.mode])
except pulsectl.PulseOperationFailed as e:
print("Failed to set %s on %s: %s" %
(args.mode, headset.proplist['device.description'], e))
if args.mode == 'a2dp':
print("Push the button on the headset!")
sys.exit(1)
sys.exit(0)
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment