Applescript: "can't get tab group 1 of window" (El Capitan)

The following is an applescript that I use to change audio output devices:

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"
        tell tab group 1 of window "Sound"
            click radio button "Output"
            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
                set deviceselected to "Headphones"
            else
                set selected of row 2 of table 1 of scroll area 1 to true
                set deviceselected to "MX279"
            end if
        end tell
    end tell
end tell
tell application "System Preferences" to quit

It worked on Yosemite, but when I updated to El Capitan it is giving me the following error:

"System Events got an error: Can't get tab group 1 of window \"Sound\" of application process \"System Preferences\". Invalid index"

I'm pretty unfamiliar with applescript, so any ideas why this might be happening will be much appreciated.


Solution 1:

In the first part of your script you load the Sound preference pane. It can happen that the pane isn't fully loaded before you send commands to it in the second part of the script. The error says that the tab group 1 (the one that contains the Output tab) doesn't exist at the moment you are trying to access it.

To make sure the tab group 1 exists, we can wait for it with these two lines:

repeat until exists tab group 1 of window "Sound"
end repeat

The full script:

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"
            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
                set deviceselected to "Headphones"
            else
                set selected of row 2 of table 1 of scroll area 1 to true
                set deviceselected to "MX278"
            end if
        end tell
    end tell
end tell
tell application "System Preferences" to quit