Skip to content

Instantly share code, notes, and snippets.

@cyberorg
Forked from ef4/usb-headset.sh
Last active August 29, 2015 14:02
Show Gist options
  • Save cyberorg/0080233d204236e6e662 to your computer and use it in GitHub Desktop.
Save cyberorg/0080233d204236e6e662 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Adapted from Erik Johnson's script at
# http://terminalmage.net/2011/11/17/setting-a-usb-headset-as-the-default-pulseaudio-device/
#
# Updated by Edward Faulkner <[email protected]> to move existing
# streams and eliminate the extra fork script.
# Updated by CyberOrg <[email protected]> to add more automation
#
# You'll need to change these to point at your headset device if
# autodetection does not work.
#OUTPUT="alsa_output.usb-Generic_FREETALK_Everyman_0000000001-00-Everyman.analog-stereo"
#INPUT="alsa_input.usb-Generic_FREETALK_Everyman_0000000001-00-Everyman.analog-stereo"
get_variables () {
export PULSE_RUNTIME_PATH=/var/run/user/$(id -u)/pulse
OUTPUT=$(pacmd list-sinks |grep name: |grep -i usb | cut -d \< -f2 | sed -e 's@>@@')
INPUT=$(pacmd list-sources |grep alsa_input|grep usb | cut -d \< -f2 | sed -e 's@>@@')
}
get_variables
for i in {1..5}; do
if [ x$OUTPUT == x ]; then
get_variables
sleep 3
fi
break
done
if [ "$1" == "--fork" ]; then
# When run from udev, we fork to give pulseaudio a chance to
# detect the new device
bash $0 &
elif [ "$UID" == "0" ]; then
# If we're running as root, we just forked from udev. Now sleep so
# pulseaudio can run.
sleep 3
# Check process table for users running PulseAudio
# ps ax o user:15,cmd
for user in `ps axc -o user:20,command | grep pulseaudio | cut -f1 -d' ' | sort | uniq`;
do
# And relaunch ourselves for each of those users.
su $user -c "bash $0"
done
else
# Running as non-root, so adjust our PulseAudio directly.
if [ x$OUTPUT == x ]; then
exit 0
else
pacmd set-default-sink $OUTPUT >/dev/null 2>&1
pacmd set-default-source $INPUT >/dev/null 2>&1
for playing in $(pacmd list-sink-inputs | awk '$1 == "index:" {print $2}')
do
pacmd move-sink-input $playing $OUTPUT >/dev/null 2>&1
done
for recording in $(pacmd list-source-outputs | awk '$1 == "index:" {print $2}')
do
pacmd move-source-output $recording $INPUT >/dev/null 2>&1
done
fi
fi
# Invoke from udev by creating a file like:
# /etc/udev/rules.d/85-usb-headset.rules
# Containing a rule like this (will need to be customized for your device):
#KERNEL=="card?", SUBSYSTEM=="sound", DRIVERS=="snd-usb-audio", ACTION=="add", RUN+="/usr/bin/usb-headset.sh --fork"
# Also call this script by creating /etc/xdg/autostart/usb-headset.desktop
# to ensure usb device is default if user logs in after it is plugged in
#[Desktop Entry]
#Version=1.0
#Encoding=UTF-8
#Name=usb-headset
#Exec=usb-headset.sh
#Terminal=false
#Type=Application
#Categories=
#GenericName=
#X-GNOME-Autostart-Phase=Initialization
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment