Lyle Vogtmann

Monday, December 06, 2010

 

AppleScript and cron to appease the neighbors.

I should really use this blog more often, share some of these tidbits of info I find useful and invariably forget...

I tend to work at my computer at odd hours, much to the chagrin of my upstairs neighbor. So at night, I switch to using a headset. Since I do this every night now, and it's the same "Open System Preferences -> Sound -> Output -> Headphones -> Close System Preferences" every time, I figure it's a good candidate for automation. The only scripting tool I know of that can operate the System Preferences application (besides manually editing plist files) is AppleScript. So I put together the following script with help from a little googling:

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 2
        set theRows to every row of table 1 of scroll area 1 of ¬
            tab group 1 of window "sound"
        set theOutputs to {} as list
        repeat with aRow in theRows
            if (value of text field 1 of aRow as text) ¬
                is equal to "Sennheiser USB Headset" then
                set selected of aRow to true
                exit repeat
            end if
        end repeat
    end tell
end tell
tell application "System Preferences" to quit


Saved that to my Documents folder as 'Switch2USBHeadset.scpt', and then set up the following cron job to run it automatically at 10pm daily. (Note the use of the 'osascript' command, AppleScripts aren't executable by themselves like bash/python/perl scripts.)

0 22 * * * osascript /Users/vmann/Documents/Switch2USBHeadset.scpt

The only thing I don't like about this so far is System Preferences gets input focus while the script is running, so if I happen to be typing something at 22:00 I might lose a few characters while System Preferences takes over. If anyone knows how to 'activate' an application but avoid stealing focus from any other applications currently running, please let me know!

Archives

June 2010   December 2010   January 2011  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]