In my box (details below), sound runs thruough a built-in BurrBrown PCM3052 card that handles Line Level Input, SPDIF Digital output, Headphones, Internal Speakers, and Line Level Output - the last being what I get when I plug in internal speakers. I can see all this in the System Profiler or by running this script which creates a file on your desktop with the same info:
tell application "Finder" to set tName to name of startup disk
do shell script "/usr/sbin/system_profiler > " & POSIX path of (path to desktop as text) & tName & ".profile.txt"
Clearly, the BB3052 ‘knows’ what’s plugged in, and ‘informs’ the Sound preference pane too, but I have been unable to discover how it does it - Plugging in my external speakers changes the Sound pane’s first line to “Line Out” immediately, unplugging it changes the reading to “Internal Speakers” and the controls available are switched (Internal Speakers doesn’t have a “Balance” control). Maybe a test for that…
After some fiddling, I discovered that I could get the ‘value’ of the text field that contains the ‘Line Out’, ‘Headphones’, or ‘Internal Speakers’ announcement with GUI scripting (although the test was performed with the Sound Pane Open, so you may have to do that first):
activate application "System Preferences"
tell application "System Events" to tell process "System Preferences" to set S to value of text field 1 of row 1 of table 1 of scroll area 1 of tab group 1 of window "Sound"
so you could test to see what it said and act accordingly. Your mileage may vary.
EDIT: If System Preferences is NOT running (which it won’t be at startup), this works (but fails if SP is open to a pane so quit SP before you try it):
activate application "System Preferences"
tell application "System Events" to tell process "System Preferences"
click button "Sound" of scroll area 1 of window "System Preferences"
delay 1
set S to value of text field 1 of row 1 of table 1 of scroll area 1 of tab group 1 of window "Sound"
end tell
You would then test the value of S and set your output volume accordingly.