Audible fun with Alfred

I’ve been looking more and more at using AppleScripts in Alfred, my launcher/productivity app for Mac OS X. Today’s snippet is about switching the active audio output device; I wanted this for work, where I switch between external speakers and some headphones plugged into the front 3.5mm jack.

This script is modified from a post on SuperUser, where it started life as a snippet to toggle between two fixed devices. I wanted a little more flexibility, so I decided to use Alfred’s script parameter to take a keyword defining the device to switch to. I have this script bound to the audio keyword in Alfred, so I can type (for example) audio speakers and have music start playing through my line-out speakers. Without further ado:

property speakers : "Line Out"
property headset : "Headphones"
property optical : "Digital Out"

on alfred_script(q)
    if q is equal to "speakers" then set desired_output to speakers
    if q is equal to "headset" then set desired_output to headset
    if q is equal to "optical" then set desired_output to optical

    tell application "System Preferences" to activate
    tell application "System Events"
        get properties
        tell process "System Preferences"
            click menu item "Sound" of menu "View" of menu bar 1
            delay 1
            click radio button "Output" of tab group 1 of window "sound"
            delay 1
            set theRows to every row of table 1 of scroll area 1 of tab group 1 of window "sound"
            repeat with aRow in theRows
                if (value of text field 1 of aRow as text) is desired_output then
                    set selected of aRow to true
                    exit repeat
                end if
            end repeat
        end tell
    end tell
    tell application "System Preferences" to quit
end alfred_script

One of the current downsides to the script is that it can’t operate in the background; much like my previous script to make a Genius playlist, this brings a window to the foreground (at least briefly). As such, you should give it two or three seconds to run and dismiss the window again before you go back to what you were doing. Dedicated programs, such as Rogue Amoeba’s Sound Source, have fewer limitations.