Skip to content

Instantly share code, notes, and snippets.

@ipwnponies
Created January 16, 2021 00:04
Show Gist options
  • Save ipwnponies/2eabf2816d62139718133fd8502a231c to your computer and use it in GitHub Desktop.
Save ipwnponies/2eabf2816d62139718133fd8502a231c to your computer and use it in GitHub Desktop.
Switch sound source on OSX
(*
Applescript to toggle to laptop speakers.
Based on code by tetsujin: https://apple.stackexchange.com/a/218223
This is more dynamic, as ordering of items is not guaranteed. Sources exist temporarily,
such as bluetooth headsets or headphone jack.
Motivation:
This script use case is to toggle between the built-in speakers (always exist) and the intended headset.
I'd toggle this to temporarily switch to laptop speakers for presentation or to step away from computer
but want to continue to receive sound notifications.
*)
set outputA to "MacBook Pro Speakers" -- default, will always exist
set outputB to "External Headphones" -- headset
set outputBFallback to "S32D850" -- another headset
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.sound"
end tell
tell application "System Events"
tell application process "System Preferences"
repeat until exists tab group 1 of window "Sound"
end repeat
tell tab group 1 of window "Sound"
click radio button "Output"
set outputs to table 1 of scroll area 1
set outputARow to (row 1 where value of text field 1 is outputA) of outputs
try
set outputBRow to (row 1 where value of text field 1 is outputB) of outputs
on error errMsg
set outputBRow to (row 1 where value of text field 1 is outputBFallback) of outputs
end try
if (selected of outputARow) then
select outputBRow
else
select outputARow
end if
end tell
end tell
end tell
tell application "System Preferences" to quit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment