AppleScript for connecting to Airplay devices

To display the currently used Device (up to two):

if application "Music" is running then
	tell application "Music"
		try
			set AirPlayName1 to name of the first AirPlay device whose selected is true
		end try
		try
			set AirPlayName2 to name of the second AirPlay device whose selected is true
		on error
			set AirPlayName2 to ""
		end try
	end tell
	set AirPlayDevices to AirPlayName1 & "
" & AirPlayName2
	
else
	set AirPlayDevices to "AirPlay" & "
" & "Devices"
end if

return AirPlayDevices
--code by @Caliguvara

To get a list of all speakers you need several widgets (I use the Touch Bar). Each widget should display this script:

if application "Music" is running then
	tell application "Music"
		set listOfAirPlayNames to (get name of every AirPlay device)
		set AirPlayDevice to the first item of listOfAirPlayNames
		return AirPlayDevice
	end tell
else
	return ""
end if
--code by @Caliguvara

The executable script of the widget would be

tell application "Music"
	set listOfAirPlayNames to (get name of every AirPlay device)
	set chosenAirPlayName to the first item of listOfAirPlayNames
	set current AirPlay devices to AirPlay device chosenAirPlayName
end tell
--code by @Caliguvara

Make as many widgets as you have receivers. Replace "first" with "second", "third",… in each script. Et voilà! Hope it helps.

1 Like