Automatically regulating volume on a USB headset with Ubuntu

When you connect an external speaker or headset to your computer you normally expect the sound to play over those and you’d also expect the integrated speakers to mute. Windows does that well and you’d expect that Ubuntu can do that as well, unfortunately it doesn’t. Not without some scripting. So here we go:
The script usb-headset.sh
[2014.07.26] https://github.com/ggeorgovassilis/linuxscripts 
#!/bin/sh
echo Adjusting volumes for usb-headset
case $1 in
"deferred")
 echo running deferred
 sleep 2
 su -c "pacmd set-sink -mute alsa_output.pci-0000_00_1b.0.analog-stereo 1" george
 su -c "pacmd set-sink-mute \"<alsa_output.usb-Logitech_Inc_Logitech_USB_Headset_H540_00000000-00-H540.analog-stereo\" 0" george
 ;;
*)
 echo deferring
 ($0 deferred)&
 ;;
esac

You have to replace a few things here:

alsa_output.pci-0000_00_1b.0.analog-stereo is the sink name of integrated speaker you want to mute when connecting the usb headset. You’ll find that out with

pacmd list-sources

and a little experimenting.

george is the user who is running pulseaudio. Since the script is run as root by udev, I didn’t see an obvious way of obtaining the user programmatically. You probably want to replace it with your login.

alsa_output.usb-Logitech_Inc_Logitech_USB_Headset_H540_00000000-00-H540.analog-stereo
 is the output sink name of the USB headset. You’ll find that one out again with

pacmd list-sources

Tip: don’t forget to plug in the USB headset or you won’t see the sink name
Tip: don’t forget to chmod a+x usb-headset.sh

The udev rule /etc/udev/rules.d/100-usb-headset.rules

ACTION=="add", ATTRS{idVendor}=="046d", ATTRS{idProduct}=="0a37", RUN+="/home/george/bin/scripts/usb-headset.sh" 

Tip: Make sure the path in “run” points to the correct script location
Tip: Replace the vendor and product IDs with the ones for your USB headset – you’ll get them from lsusb in the form of vendorid:productid. More on that here [1]

[1] How to run a script when a specific flash-drive is mounted?
http://askubuntu.com/questions/25071/how-to-run-a-script-when-a-specific-flash-drive-is-mounted

[2] github https://github.com/ggeorgovassilis/linuxscripts

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.