Basic iTunes based whole house Audio control from Vera Scenes

Let me start off by saying that if I were just setting out to create a “whole house audio” system on the cheap with the mind to integrate it with Vera, I would most likely go with the Slingbox based solution that you will find information about elsewhere on the forums. From my research I have found that solution to be more flexible, more hackable, and have better sound quality than Itunes with Airtunes. That being said, I had already built my iTunes/Airtunes network including 5 airport expresses before discovering Vera, so from lemons I am making lemonade. For better of for worse, my setup actually works quite well.

I have a dedicated mac mini that I use to run an iTunes instance, as well as a Plex media player (connected to my TV) but this can also be used just as effectively on your regular mac based workstation (I started out on my office Mac pro). Note that this solution is MAC ONLY, sorry Windows iTunes users. Most of the logic used here is applescript, that runs on the mac hosting iTunes. The need for luup in scenes code is actually quite minimal but could be expanded to include more logic with someone with a greater imagination than I.

Below are the steps I followed to enable playlist based iTunes control, and well as basic start stop functionality to my Vera scenes. I have one scene called “Dinner Time” for example that turns down my living room lights, brings my dining room overhead dimmer up to 65% turns on some accent lights before connecting to iTunes and setting output to my kitchen and living room stereo speakers and playing a playlist called “Dinner Time” on a random shuffle. This sets the mood nicely for a nice meal with friends, and requires only pressing one button on my HA09 remote or VRCS4.

[ul][li]Step 1 - Setup your Mac’s (Apache) Web Server to control iTunes from web requests[/li][/ul]

This step involved making changes to core system config files as root, so be sure you know what you are doing before attempting. Please understand that the changes you are making will allow people with http/https access to your machine to execute commands AS YOUR LOCAL USER, so be extremely careful with how this is setup. I run iTunes as a dedicated user, on a machine that only hosts my media, and is not in anyway accessible from the outside network to keep my risk low, even then I understand that this strategy carries an inherent security risk.
There is a handy guide on how to accomplish this here: [url=http://www.whatsmyip.org/itunesremote/]http://www.whatsmyip.org/itunesremote/[/url].
Once this is done you can control iTunes from any web browser by entering the appropriate URL - nice.

[ul][li]Step 2 - Modify iTunes control script to include AirTunes integration, and playlist control[/li][/ul]

If you followed the guide listed in Step 1 - you will already have the ability to control basic functions (start/stop/next/prev/etc) of your iTunes from a URL. If this is all you want, skip to step 4. Most of us however will want to get a little fancier with this setup to be able to do the things I described above with my Dinner Time solution. This will require modifications to the PHP file which was called “control.php” in the guide, as well as some custom applescript as defined in Step 3.

Here is Mine with the dinner time example:

 <html>
<head>

</head>
</body>
<?
$q = $_GET['q'];

switch ($q)
{
case "":
echo "You need to send me a command, then I shall execute it";
break;

case "play";
exec("osascript -e 'tell app \"iTunes\" to play'");
echo "Playing";
break;

case "pause";
exec("osascript -e 'tell app \"iTunes\" to pause'");
echo "Pausing";
break;

case "playpause";
exec("osascript -e 'tell app \"iTunes\" to playpause'");
echo "Toggling Play";
break;

case "next";
exec("osascript -e 'tell app \"iTunes\" to next track'");
echo "Next Track";
break;

case "prev";
exec("osascript -e 'tell app \"iTunes\" to previous track'");
echo "Previous Track";
break;

case "louder";
exec("osascript -e 'tell app \"iTunes\" to set sound volume to sound volume + 5'");
echo "Turning Up the Volume";
break;

case "quieter";
exec("osascript -e 'tell app \"iTunes\" to set sound volume to sound volume - 5'");
echo "Turning Down the Volume";
break;

case "mute";
mutev();
echo "Muting the Volume";
break;

case "script_dinner";
exec("osascript /[SCRIPT PATH]/script_dinner.scpt");
echo "Executing Dinner Time Script";
break;
}


function mutev()
{
echo "start mute function<br>";

$data = file_get_contents("/Library/WebServer/Documents/volume.txt");

$logfile = fopen("/Library/WebServer/Documents/volume.txt",'w');

$oldvolume = exec("osascript -e 'tell app \"iTunes\" to sound volume'");

echo "volume data:$data:<br>";
if ($data == "x")
{
fwrite($logfile,$oldvolume);
exec("osascript -e 'tell app \"iTunes\" to set sound volume to 0'");
}
else
{
fwrite($logfile,"x");
exec("osascript -e 'tell app \"iTunes\" to set sound volume to $data'");
}
fclose($logfile);
}

?>
 

[ul][li]Step 3 - Creating the Applescript to handle playlists/Airtunes control. [/li][/ul]

This could be done in several ways. For the sake of simplicity I have a script for each “scene” that will involve complex configuration. Each of which are called by the PHP commands as you have already seen (see script_dinner example above). I will be the first to admit that I am not an Applescript expert. Also, Apple have deliberately or otherwise made it quite difficult to control Airtunes from script. The method you see here works, but definitely falls under the “hack” category. As of now, I am navigating the Airtunes speaker menu and multiple speaker popup window by element number so there is a potential instability here that if one or more of your airport expresses is off the network, thus changing the number if items in each list, it may break. I have good reason to believe that it is possible to do this navigation explicitly by name, but have not sorted out how. (feel free to fix this and report back) :slight_smile:

You will need to enable the “Enable access for assistive devices” in your iTunes system’s Universal Access preference pane for this to work. This setting allows scripts to interact with the system by emulating keyboard and mouse input.

Here is my dinner time applescript as referenced by the above PHP command ‘script_dinner’.

EDIT: See [url=http://fall-line.com/2010/09/control-airplayairtunes-feature-of-itunes-with-applescript/]http://fall-line.com/2010/09/control-airplayairtunes-feature-of-itunes-with-applescript/[/url] or the below post in this thread for iTunes 10 version

-- Remember to turn on access for assistive devices.
-- Working as of July 2010 with iTunes 9.2


activate application "iTunes"
tell application "System Events"
	tell application process "iTunes"
		
		if (name of button 16 of window "iTunes" as text) ≠ "" then
			click button 16 of window "iTunes" --Press the iTunes Speaker Button
			delay 0.01
			-- Traverse down the list of speakears (up to 7) -- If you have MORE than 6 airport Express units, make this a larger number to accomodate.
			repeat with i from 1 to 7
				key code 125
			end repeat
			keystroke return
			repeat with i from 1 to (count of every UI element of window 1)
				tell UI element i of window "Multiple Speakers"
					
					set rowcount to count of rows
					if rowcount > 0 then -- Do we have Speakers available? 
						
						-- Note that if your list of speakers changes at any point (due to an airport express being powered off, etc) the selection by row # will break. 
-- If you rename them, changing their alphabetical order, you will be turning on the wrong speaker. 
-- This logic needs to be fixed by someone who knows iTunes scripting better than I do. 
						
						
						
						-- Turn on the Kitchen Speaker (row 2) if it is off
						if (value of checkbox 1 of row 2) as integer = 0 then
							click checkbox 1 of row 2
						end if
						
						-- Turn on Living Room Speaker (row 1) also, if it is off.
						if (value of checkbox 1 of row 1) as integer = 0 then
							click checkbox 1 of row 1
						end if
						
						-- Now that we have enabled another speaker (satisfying iTunes), we can shut off the computer speakers
						if (value of checkbox 1 of row 5) as integer = 1 then
							click checkbox 1 of row 5
						end if
						
						
					end if
					
				end tell
			end repeat
			
			
		end if
		
	end tell
end tell


-- Finally, play the Dinner Time playlist. All you need to do here is create a playlist called "Dinner Time", etc.

tell application "iTunes"
	set shuffle of playlist "Dinner Time" to 0
	set shuffle of playlist "Dinner Time" to 1
	play playlist "Dinner Time"
end tell



[ul][li]Step 4 - Include Luup URL calls in the appropriate Vera scenes to have them execute your iTunes commands when executing[/li][/ul]

From my “Dinner Time” Vera Scene’s Luup code:

[code]luup.inet.wget(“http://[ITUNES HOST]/control.php?q=script_dinner”)

Replace [ITUNES HOST] with your IP address or hostname
[/code]

From my “Good Night” scene that turns off all lights and stops iTunes if it is playing:

[code]luup.inet.wget(“http://[ITUNES HOST]/control.php?q=pause”)

Replace [ITUNES HOST] with your IP address or hostname
[/code]

[ul][li]Step 5 - Going beyond[/li][/ul]

One of the limitations of using iTunes as a whole house adio system with our without vera integration is with the airport express outputs. Most users simply connect them to an existing stereo etc since they do not themselves provide amplified speaker connections. This means you have to go turn on the stereo in each room and set the appropriate input in most cases - not ideal for the one touch integration we are looking for. You can remedy this problem by either integrating your stereo into Vera as well (via IR, RS-232, etc) and/or by including auto-on amplifiers/speakers with your Airport express such as these:

[ul][li]ZVOX Mini[/li]
[li]Audioengine A5[/li]
[li]AudioSource AMP-100[/li][/ul]
(I use this with some Polk bookshelf speakers)
Each of the above options will sit in a low power ‘sleep’ mode until such time as there is a signal detected on the audio in port, and then will power up and start playing your tunes.

If your iTunes machine is not always on, I would also recommend enabling the “Wake for Ethernet network access” (WOL) feature in your system’s power saver settings so that it will wake from sleep when you attempt to control it.

Other ideas:

[ul][li]Play a specific playlist when a code is used to unlock your Schlage door lock, welcoming you home[/li]
[li]Play & repeat a specific track over all speakers as an alarm for certain conditions[/li]
[li]Subtly dim the lights and put on a nighttime soundtrack in a kids room before bedtime[/li]
[li]You tell me… [/li][/ul]

I hope this helps a few of you to reproduce the setup I have here, or provides you the information you need to customize it to your own desires, and improve on it! It certainly isn’t perfect, but I must admit it is pretty slick at times. I’d be happy to try and answer any questions… but everybody’s system is different. Like I mentioned above this is probably a solution best left to those who have some experience with scripting and who are comfortable working in the terminal of their Macs.

Cheers

Nice post. It’s great to hear about the different things people are integrating with Vera.

The list of amps and speakers that activate when they detect a signal is interesting too. While I’m a squeezebox boy myself, I have ambitions of using a Squeezebox Duet (speakerless) with external speakers mounted in the roof. Something like those amps would help a lot.

EDIT: Noticed that only one of the three was an amp - still a good list, and those Audioengine A5’s seem to review very well.

@Klunket

Yeah, the A5’s are probably what I would have bought if I hadn’t already had a nice set of bookshelf speakers to use. So far I’ve been very impressed with the AMP-100 (bought it from Newegg for $99).

Wonderful post, is there similar way to control itunes on a apple tv since apple tv does not have osascript installed. Thanks !

Sorry @sugiths, I don’t know of a way to incorporate this into your AppleTV based iTunes setup. I’m not saying it’s not possible, but I don’t have one to play with, and a quick google search didn’t yield anything obvious. I have heard that some people have hacked their ATVs pretty well to add functionality, but don’t know if applescript is among the possibilities.

It’s technically possible to do AppleTV, iTunes (etc), but the API/Interaction to do it “natively” is going to be a bunch of work for someone to implement.

For anyone interested, the raw Protocol bits are outlined here:

http://dacp.jsharkey.org/

but it will require a bunch of work to translate to Lua/Luup (etc) given the myriad of mDNS and other “initial” handshaking that has to occur before you can fire off the native URLs against the device (iTunes or AppleTV) - basically there’s a key-exchange of sorts “up front” when you enter the codes into the iTunes and/or AppleTV display, and this handshake will require some thought.

In addition to the above URL/Protocol Documentation, I’ve seen some that refer to more “Remote Control” centric API calls (“moveUp”, “moveLeft”, “select”, etc, etc) but I don’t have that handy right now.

As a side-note, mDNS is going to be one of those “libs” that we eventually need wrappered in Lua in order to “locate” things to talk to (for plugins). I have a hacked together mDNS impl, but it’s got a lot of limitations right now.

Either way, it wont be nearly as simple as @fall-line’s posting here.

OMG fall-line, you are my new best friend, lol

I have been working with my 3 Airport Express units for a while and just using them with Apple Remote on iTouch and some cheap amplified computer speakers for testing purposes. I am relatively new to Mac, with my Mini, and would love to follow your lead here.

I’ve dipped into Plex, bought EyeTV with an HDPVR and change channels on my Fios box via Firewire, also the Air Tunes thing, but haven’t mastered all three. It is hard to decide whether to go all Apple and have a Mac Mini at each TV or mix it with W7 Media Center/XBOX360 or now, after reading your setup, I’m thinking dedicate the mini as an audio server and let W7 do the DVR stuff.

Vera and Scene integration of Air Tunes sounds great and rather smooth. As it is now, I have my Airport Expresses on Z-Wave controlled outlets that I first turn on in SQ Remote, wait for them to join Wi-Fi, then while that is happening, I VNC on the iTouch to launch iTunes on the mini, jump over to the Apple Remote and find my iTune Library, then hit play, LOL. I know it is brutal, but the only reason I have the Airports on Z-Wave is to reduce Vampire power consumption (they’re only .2 amps or 22 watts), but I believe a scene could do all of this for me. You’ve given me some motivation and direction to clean this up. Anyways I’ll have to wait 'til next weekend, but I look forward to your help. Thank you for the amp recommendations as I eventually want in-ceiling speakers, too.

Glad I could help Shady! I’ll be picking your brain some more about recommendations on motorized window treatments in the coming year, so I’m happy I can be of help to you as well.

Without getting this thread too far off topic (we can chat about Plex - which is AWESOME - and the like in PM if you want) here are a few thoughts:

I was concerned about vampire power with the airport express units being left on 24x7 as well, but after plugging them into a Kill-A-Watt I measured them at 1watt when idle, occasionally peaking at 2watts. When audio is playing, they shoot up to 12-16 watts if I recall. Personally I really like the ability to control iTunes/Airtunes in a standard way (from my phone with apple remote or from the computer itself) and choosing appropriate output locations spontaneously, so I wouldn’t want to be required to enable z-wave outlets and wait 15-30 seconds before being able to start playing there. That being said, I’m all for reducing vampire power draws in the home so if that works for you, go for it. You could definitely have a scene that turns them on, wakes up your computer, launches itunes (any of the applescript commands in that PHP file will open itunes if it isn’t already open), selects the speakers, and hits play. Just be aware that the applescript code as it exists today in my script will be very flaky if you try to run it with inconsistent numbers of airport express units each time.

I’ve updated the applescript portion of this process to work with iTunes 10. I was also able to build in some more smarts to the script, so it will be resilient to changing alphabetical structure and individual airtunes endpoints coming online and offline. I’m actually pretty happy about this because this (having some units offline at times) was the one thing that prevented me from using this scene regularly for dinner with guests.

It kind of took the magic away to have to say, excuse me while I run down to the basement and plugin my airport express so that the computer will be able to play to the other airport express here in the dining room when I press this little button on the wall here. :slight_smile:

Here is the updated code for iTunes 10 (only):

-- Remember to turn on access for assistive devices.
-- Working as of September 2010 with iTunes 10 only. 
-- See http://forum.micasaverde.com or http://fall-line.com for iTunes 9 version.




activate application "iTunes"
tell application "System Events"
	tell application process "iTunes"
		
		click button 8 of window "iTunes" --Press the iTunes 10 Speaker Button
		key code 125 using {command down} -- this is essentiall hitting page down (command + down arrow)
		delay 0.1
		keystroke return
		
		tell window "Multiple Speakers" of application process "iTunes" of application "System Events"
			activate -- Make sure we are on the right window
			tell table 1 of scroll area 1
				activate -- Drill into the Table that contains our speakers
				
				-- "Computer" should always be row #1 since it is immune to the alphabetizing iTunes does to the rest. If it is off, turn it on first, so that we can modify the status of others in any way we please without getting an error.
				if (description of checkbox 1 of group 1 of row 1) = "Computer" and value of checkbox 1 of group 1 of row 1 as integer = 0 then
					click checkbox 1 of group 1 of row 1
				end if
				
				repeat with i from 1 to (count of every row) -- Itterate through each row, looking for the criteria below
					
					set rowcount to count of rows
					if rowcount > 0 then
						
						tell group 1 of row i
							activate -- Drill into the object group of each row, so we don't have to later.
							
							
							
							if (description of checkbox 1) = "AAA" and value of checkbox 1 as integer = 0 then
								click checkbox 1
							end if
							
							if (description of checkbox 1) = "BBB" and value of checkbox 1 as integer = 0 then
								click checkbox 1
							end if
							
						end tell
					end if
					
				end repeat
				
			end tell
		end tell
		
	end tell
end tell

-- Finally, play the Dinner Time playlist. All you need to do here is create a playlist called "Dinner Time", etc.
tell application "iTunes"
	set shuffle of playlist "Dinner Time" to 0
	set shuffle of playlist "Dinner Time" to 1
	play playlist "Dinner Time"
end tell

EDIT: This script will continue to be updated as future versions of iTunes are released here:
http://fall-line.com/2010/09/control-airplayairtunes-feature-of-itunes-with-applescript/

I’m looking forward to seeing what Apple and their 3rd party partners do with the new “AirPlay” standard.

Thank you so much for the great posts!

Please pardon my ignorance. I am not very experienced dealing with audio setups. I would be thankful for any advise you could give me!

I have a pretty big house with speakers in the ceilings.
Probably 6 rooms upstairs (2 speakers each room)
4-6 rooms downstairs

I have an Imac with a big external drive and a couple of macbooks, appletv, airport express, home sharing working

All the speaker wires terminate in a media closet (don’t even have connectors on the wires)

All I want to do is to use the remote app (or some other app) from iphone or itouch to control what speakers are “on”, volume control of the “on speakers”, and what is playing on itunes. I know I need some type of amplifier— I assume I could use an airport express as an input source but I don’t know how this will work with volume control etc. because I would anticipate I will need to control the itunes source and the amplifier zone and volume. I am confused.

If I could have even 2 zones playing different things it would be awesome

I had the house wired many years ago but I never could find a good solution that didn’t require enormous costs with all the high dollar home automation hard/software. I dont know why this seems so hard to do! It seems like all the installers want to rip you off with big dollar hardware and programming fees.

Thank you
bobdds@me.com

Bob,

You are fortunate to have your whole house wired with speaker wire (and speakers!). Good on ya for that. You have a huge number of options to choose from, and can expect a pretty high quality solution when you are finished. The solution that I outlined above is more targeted at the rest of us out there, who don’t have our houses pre-wired, and only have a few choices for “whole house audio”.

That being said, you can definitely implement my solution if you specifically want to use iTunes as a source with the Apple iOS remote app for control. You will need to install a multi zone amplifier in your closet and hook up a single airport express to it as an input (unless you can connect your mac directly to it?). You have several options for controlling the speaker on/off & volume. Some newer amps have their own iOS remote control applications (see the latest Pioneer models for an example), but you can also take advantage of the newly released SQ Blaster device from Square Connect. This is a little IR blaster that sits near your gear and allows you to control it from the SQ Connect application on your i(Phone/Pad/Pod). This would mean using one app to control the music itself and another for the speaker control, but it has the added benefit of allowing you to control other aspects of the amp as well (say other media sources, radio, etc) not to mention the other vera specific benefits of SQ Connect.

Otherwise, as I said you are fortunate to have the speakers all wired. If I were you, I’d look seriously at a more advanced whole house audio system that will give you features like playback of separate sources or tracks in different zones. There are a lot of systems out there (Search: Sonos, Control 4, Savant, etc) You’ll end up spending a little more on these, but they are worth consideration.

Good luck to you in your setup. You may want to check with the folks over at avsforum.com as well.

Heads up to anyone doing this - iTunes 10.1 breaks the script. Apple did some goofy things to the Multiple Speakers UI elements that makes it even more tricky to script (it was hard enough as it was). It is as if Apple is deliberately trying to prevent this scripting… >:(

Anyway, I’ll work on a fix when I can, in the mean time you should consider sticking with iTunes 10.0.x if you are relying on this.

I’ve managed to update the script to work well with iTunes 10.1. Rather than continuing to paste large blocks of code into this thread (I can see this is going to be a continuing theme), I’ll simply refer you to my website where this is kept up to date:
[url=http://fall-line.com/2010/12/control-airplayairtunes-in-itunes-101-with-applescript/]http://fall-line.com/2010/12/control-airplayairtunes-in-itunes-101-with-applescript/[/url]

Cheers

An update regarding iTunes 10.3?

I haven’t upgraded iTunes on my main home machine past 10.1 due to this script, but am planning to try and update the script for 10.3+ compatibility shortly.

Good news, I’ve just upgraded to iTunes 10.3.1, and this script continues to work without further modification.

Let me know if you have any troubles.

Fall-line

Absolutely great set of scripts. I look forward to implementing this tonight.

To avoid any complications, have you tested your setup with the newest 10.5 release?

You should be good with 10.5 as I don’t think Apple changed anything relating to how Airtunes/Airplay works in recent releases. @Fall-line’s last change to the plug-in/scripts was because Apple made changes in how Airtunes worked, changing it to Airplay in iTunes 10.1. I’d say it should work in 10.5, but please report back and let us know.

Hi,

very interesting topic. I’m using the Apple Tv via IR with Vera, as now with iCloud i don’t need more iTunes opened in the Mac.

But it would be great if we can run playlist or song via scene of Vera.

I didn’t find this feature still develop.

Did Somebody try something on it?

Thank guys
Matteo