Skip to content

Instantly share code, notes, and snippets.

@un-def
Created January 27, 2022 21:15
Show Gist options
  • Save un-def/280bb41cc927ecc4770a1c075c83295a to your computer and use it in GitHub Desktop.
Save un-def/280bb41cc927ecc4770a1c075c83295a to your computer and use it in GitHub Desktop.
Switch PulseAudio sinks
#!/usr/bin/env bash
die() {
notify-send "${NOTIFICATION_SUMMARY}" "${1}" -i audio-volume-muted -t 3000
exit 1
}
config_path="${XDG_CONFIG_HOME:-$HOME/.config}/switch-sink.conf.bash"
[[ -f ${config_path} ]] || die 'Config not found'
# shellcheck disable=SC1090
source "${config_path}"
declare -A sink_pa_names_map
for full_pa_name in $(pacmd list-sinks | grep -oP '(?<=name: <)[^>]+'); do
short_pa_name=$(echo "${full_pa_name}" | awk -F. '{OFS=".";NF-=1;$1="";sub(".", "");print}')
sink_pa_names_map[${short_pa_name}]="${full_pa_name}"
done
current_pa_name="$(pactl get-default-sink)"
next_index=0
declare -a sink_pa_names
declare -A card_human_names_map
for index in "${!CARDS[@]}"; do
card=${CARDS[${index}]}
read -r short_pa_name human_name <<< "${card}"
full_pa_name=${sink_pa_names_map[${short_pa_name}]}
sink_pa_names+=("${full_pa_name}")
card_human_names_map["${full_pa_name}"]="${human_name}"
[[ ${full_pa_name} == "${current_pa_name}" ]] && next_index=$((index + 1))
done
[[ ${next_index} -ge ${#CARDS[@]} ]] && next_index=0
next_sink_pa_name=${sink_pa_names[${next_index}]}
next_sink_human_name=${card_human_names_map[${next_sink_pa_name}]}
pactl set-default-sink "${next_sink_pa_name}" || die 'Failed to switch'
notify-send "${NOTIFICATION_SUMMARY}" "${next_sink_human_name}" -i audio-volume-high -t 2000
[[ -z "${TRAY_APP}" ]] && exit
killall -e "${TRAY_APP}" 2> /dev/null
${TRAY_APP} &
CARDS=(
'pci-0000_0c_00.4 Speakers'
'pci-0000_0a_00.1 Display'
'usb-KTMicro_KT_USB_Audio_2021-06-07-0000-0000-0000--00 USB Card'
)
TRAY_APP='volumeicon'
NOTIFICATION_SUMMARY='Audio Output'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment