Set Sound Output via AppleScript

When playing music I usually change my office MacBook’s sound output to a Sonos speaker, which is an AirPlay device. Sometimes the connection freezes and I have to reset output my default device and back to the office speaker. I wanted to automate both of these processes, so I found an AppleScript as a starting point. I modified it and created an Alfred Workflow with a keyword trigger. Here’s my version of the AppleScript. Feel free to modify it for your own use.

-- This script can be used to set/reset the sound output
-- Two devices because sometimes the AirPlay device loses connection
set myDevices to {"LG UltraFine Display Audio", "Office"}

tell application "System Settings"
	-- sometimes it is already open to Sound, which causes an error
	quit
	delay 0.3
	activate
	delay 0.3
	
	tell application "System Events"
		tell process "System Settings"
			set theWindow to first window
			delay 0.3
		end tell
		
		keystroke "Sound"
		delay 1
		
		tell application process "System Settings"
			tell radio button 1 of tab group 1 of group 2 of scroll area 1 of group 1 of group 2 of splitter group 1 of group 1 of window "Sound"
				click
			end tell
			
			delay 0.5
			
			set theRows to (every row of table 1 of scroll area 1 of group 2 of scroll area 1 of group 1 of group 2 of splitter group 1 of group 1 of window "Sound")
			
			repeat with myDevice in myDevices
				set device to myDevice as string
				repeat with aRow in theRows
					try
						if name of first item of static text of group 1 of UI element 1 of aRow is equal to device then
							set selected of aRow to true
							
							exit repeat
						end if
					on error
						display dialog "Error setting output sound to " & device
					end try
				end repeat
			end repeat
		end tell
	end tell
	
	quit
	
end tell