Here's the Python script that I use:
#!/usr/bin/env python
# This script monitors USB connections and when the audio device is connected
# makes it the default output device.
import dbus, gobject, os
from dbus.mainloop.glib import DBusGMainLoop
from subprocess import Popen, PIPE
PCI_DEVICE = 'alsa_output.pci-0000_00_1b.0.analog-stereo'
USB_DEVICE = 'alsa_output.usb-Logitech_Logitech_Z205-00-default.analog-stereo'
def set_default_sink(sink):
popen = Popen('pacmd', stdin = PIPE, stdout = PIPE)
popen.communicate('set-default-sink ' + sink)
def device_added(udi):
if udi.find('alsa') >= 0:
set_default_sink(USB_DEVICE)
def device_removed(udi):
if udi.find('alsa') >= 0:
set_default_sink(PCI_DEVICE)
DBusGMainLoop(set_as_default = True)
bus = dbus.SystemBus()
hal_manager = bus.get_object('org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
bus.add_signal_receiver(device_added, 'DeviceAdded',
'org.freedesktop.Hal.Manager', 'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
bus.add_signal_receiver(device_removed, 'DeviceRemoved',
'org.freedesktop.Hal.Manager', 'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
gobject.MainLoop().run()
The sink names (PCI_DEVICE for the internal speakers and USB_DEVICE for the USB speakers) are specific to my machine, so you'll need to replace them. You can get these names from pacmd which is a part of pulseaudio-utils - just enter list-sinks in the pacmd prompt and find the names of your devices (USB speakers must be connected).