My impression is:
Toggle item A:
“Internal Speakers”/“Headphone port”
Toggle item B: ?
Thanks for asking, ccstone.
In your format, toggle item A can be one of either:...
“Internal Speakers" or "Headphones”
... in my System Preferences, depending on whether the headphones are physically plugged in or not. The System automatically detects whether they are plugged in, and changes its Preferences text accordingly, and...
Toggle item B: "C_Media USB Audio Device"
The wording of toggle item B doesn't change, unless the device itself isn't plugged into a USB port, in which case your code alerts me to the fact it's not there.
In your code, which works fine as is, if the headphones happen to be plugged in, then the Preferences wording changes and the code fails.
After reading your KM variable settings steps and your code script that follows (I know little about the coding), I was thinking what was needed was that KM, maybe, should do an IF-THEN-ELSE test before invoking your script, something like:
IF the System Preferences is set to "Internal Speakers" OR "Headphones" THEN switch to "C_Media USB Audio Device"
But I don't know how to query the System, by changing your KM steps or code, about the state of the Preferences's current setting, whether it's “Internal Speakers” or "Headphones". I'm guessing that KM should do the IF-Then test and branch accordingly so that it sets up your script properly. But maybe it works better if the script wording is adjusted in some way.