Skip to content

Instantly share code, notes, and snippets.

@joshellington
Created January 1, 2025 21:08
Show Gist options
  • Save joshellington/01d4a0470172cc91aa9f987e3151ba6e to your computer and use it in GitHub Desktop.
Save joshellington/01d4a0470172cc91aa9f987e3151ba6e to your computer and use it in GitHub Desktop.
Bash script to switch between desired audio output options. Currently bound to "Page Down" key personally, using Karabiner.
#!/bin/bash
# Path to SwitchAudioSource
SWITCH_AUDIO="/opt/homebrew/bin/SwitchAudioSource"
# Get current output device
current=$("$SWITCH_AUDIO" -c)
# Define preferred devices in order
declare -a devices=(
"MacBook Pro Speakers"
"External Headphones"
"EDIFIER R1700BT"
"airpods"
)
# Function to check if a device is available
is_device_available() {
local device="$1"
"$SWITCH_AUDIO" -a | grep -q "$device"
return $?
}
# Find next available device
find_next_device() {
local current="$1"
local found=0
local next=""
# Loop through devices array
for device in "${devices[@]}"; do
# If device is available
if is_device_available "$device"; then
# If we found current device before, this is our next
if [[ $found -eq 1 ]]; then
next="$device"
break
fi
# If this is our current device, mark it
if [[ "$current" == *"$device"* ]]; then
found=1
fi
fi
done
# If we haven't found next device, use first available device
if [[ -z "$next" ]]; then
for device in "${devices[@]}"; do
if is_device_available "$device"; then
next="$device"
break
fi
done
fi
echo "$next"
}
# Find and switch to next device
next_device=$(find_next_device "$current")
if [[ -n "$next_device" ]]; then
"$SWITCH_AUDIO" -s "$next_device"
osascript -e "display notification \"$next_device\" with title \"Audio Output\""
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment