Control iTunes AirPlay streaming with AppleScript

May 20, '13 07:30:00AM

Contributed by: kirkmc

iTunes 11.0.3 provides AppleScript support for controlling AirPlay devices. Below is a basic script that illustrates how AirPlay devices can be selected and applied using some of the new iTunes AppleScript classes and properties:

tell application "iTunes"
	set apDevices to (get every AirPlay device whose available is true)
	if apDevices is {} then display dialog "No Airplay devices available." buttons {"Cancel"}
	set apNames to (get name of every AirPlay device whose available is true)
	set selAirplayDevices to (get name of every AirPlay device whose selected is true)
	set chosenNames to choose from list apNames default items selAirplayDevices with prompt "Select Airplay device:" with multiple selections allowed
	if chosenNames is false then return
	set apChoices to {}
	repeat with i from 1 to length of apNames
		if item i of apNames is in chosenNames then set end of apChoices to item i of apDevices
	end repeat
	set current AirPlay devices to apChoices
end tell
The AirPlay device class has several useful properties, including selected and available used above (check the iTunes sdef to see them all). The kind property could be used to generically select a device:

tell application "iTunes"
	# possible values for kind are computer/‌AirPort Express/‌Apple TV/‌AirPlay device/‌unknown
	set newAirplayDevice to (get some AirPlay device whose kind is computer)
	set current AirPlay devices to {newAirplayDevice}
end tell
I've also been able to use "first AirPlay device" to reference "Computer", but that may not be consistent for all users. Of course, if you have more than one of a particular kind of AirPlay device (two or more Apple TVs or AirPort Expresses), you'll need to augment that snippet, possibly by hardcoding the name of the device or by filtering for additional properties.

[kirkmc adds: This was submitted directly to me by Doug Adams of Doug's AppleScripts for iTunes.]

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20130520061835490