Is it possible to make a hotkey for switching audio output?

I am using external monitors. Because of this, whenever my mac goes to sleep, it automatically redirects output to the monitor. This is annoying to fix, as I have to move my mouse and click to fix it every time. Is there a way to set a hotkey to toggle the sound output for me? something like command+shift+s

enter image description here


Solution 1:

Since you only have the two output devices, the following code will toggle between the two.

tell application "System Preferences" to ¬
    reveal anchor "output" of pane id "com.apple.preference.sound"

tell application "System Events"
    tell application process "System Preferences"
        repeat until exists tab group 1 of window "Sound"
            delay 0.1
        end repeat
        tell tab group 1 of window "Sound"
            if (selected of row 2 of table 1 of scroll area 1) then
                set selected of row 1 of table 1 of scroll area 1 to true
            else
                set selected of row 2 of table 1 of scroll area 1 to true
            end if
        end tell
    end tell
end tell

quit application "System Preferences"

I test this as an Automator Service using a Run AppleScript action and then assigned it a hot-key combo and it works on my system having only two sound outputs. The tricky part is going to be finding a hot-key combo that isn't assigned to any or all apps already.

As an example commandshifts is Save As... in Safari, but if the Desktop has focus when pressed it works to trigger the Service.

  1. Open Automator.
  2. File > New > Service, with setting as shown in the image.
  3. Add a Run AppleScript action an replace the default code with the code Above.
  4. Save the Service as, e.g.: Toggle Sound Device
  5. Assign it a keyboard shortcut in: System Preferences > Keyboard > Shortcuts > Services

Toggle Sound Device