Changing Sound Outputs w/Applescript (I seem to have misplaced my tab group) I'm starting with the disclaimer that this is my first time posting, so if I breach etiquette, I promise it's by accident; just let me know.

I'm trying to make an AppleScript to change the sound output on my Mac with a voice command (I hurt my arms recently and have been programming automations and tying them to dictation). And while I've been able to make a lot of things work, I've had trouble with this one.

The really frustrating thing is, I can, technically, get it to work. I have made the script as follows:

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

tell application "System Events" to tell process "System Preferences"
    tell table 1 of scroll area 1 of tab group 1 of window 1
        select (row 1 where value of text field 1 is "Andrea Comm USB-SA Headset")
    end tell
end tell

quit application "System Preferences"


I can run this, and it will change my sound output to my headset. The problem is that once that's done, I can't change it to anything else until I do it manually. I literally duplicated the script and replace the name of the headset with "headphones", but when I run it, it says it can't get tab one of group 1. I even made a completely identical copy, one that also switches the output to the headset, and had the same exact problem.

But, if I go and manually reset the output, I can run this same script to change to the headphones, and it will work. Then it's the other script that won't work until I've manually changed the output again.

I've looked all over, and I cannot find a solution to this problem. No one else seems to have this issue, but I've had it across multiple scripts. And while I'm normally all about being my own special little snowflake, in this case it's not helping me any.

Any help you can provide would be great. Thanks so much!
While the other answer does in fact work for me on my system running macOS High Sierra nonetheless, I have to post a KISS principle answer.

Simply add the following code to your existing code:

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


So your code will now look like:

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

tell application "System Events" to tell process "System Preferences"
    repeat until exists tab group 1 of window "Sound"
        delay 0.1
    end repeat
    tell table 1 of scroll area 1 of tab group 1 of window 1
        select (row 1 where value of text field 1 is "Andrea Comm USB-SA Headset")
    end tell
end tell

quit application "System Preferences"


There most definitely is a level of sophistication to the other answer; however, I'd imagine it may be a bit difficult to understand for those who are new to AppleScript and why a KISS principle answer is being provided.