If you need or want more direct control over your Mac's sound devices, and want to avoid UI scripting (which can be fragile), you might consider this:
Note: I have NOT tested this personally, but it seems to be recommended by a lot of folks at StackExchange.com)
SwitchAudioSource [-a] [-c] [-t type] [-n] -s device_name
-
-a : shows all devices
-
-c : shows current device
-
-t type : device type (input/output/system). Defaults to output.
-
-n : cycles the audio device to the next one
-
-s device_name : sets the audio device to the given device by name
The price is that you have to have, or install, Xcode and Xcode's command line tools.
There are other tools that need these, and Xcode is free, so it may be work having in the long run.