Automating/scripting iTunes on Windows

Apple has posted an SDK for accessing iTunes using COM on Windows (it's funny, I noticed they left .DS_Store files in the zip archive!). It includes sample javascripts for doing things like creating playlists. You can actually write these scripts without downloading the SDK. What the sdk gives you (in addition to these samples) is the headers you'll need to access this from C with straight COM, and documentation of the object model.

An example of iterating through the tracks through javascript looks like:

var   iTunesApp = WScript.CreateObject("iTunes.Application");

var   mainLibrary = iTunesApp.LibraryPlaylist;

var   tracks = mainLibrary.Tracks;

var   i;

for (i = 1; i <= numTracks; i++)

{

      var currTrack = tracks.Item(i);

      WScript.Echo(currTrack.Name + " by " + currTrack.Artist);

}

You don't really need it though - the type library is built into iTunes.exe. For example, you can from you C# app, you can add a reference to iTunes by right clicking the references section, choosing Add Reference..., going to the COM tab, and selecting iTunes 1.0 Type Library. You can then double-click iTunesLib under references to see the object model iTunes exposes, but you are much better off with the documentation in the sdk. In C#, the same example looks like:

namespace iTunesSample

{

using System;

using iTunesLib;

class TrackLister

{

[STAThread]

static void Main(string[] args)

            {

iTunesApp app = new iTunesAppClass();

IITTrackCollection tracks = app.LibraryPlaylist.Tracks;

for(int i = 0; i < tracks.Count; i++)

{

IITTrack track = tracks[i+1];

Console.WriteLine("{0} by {1}", track.Name, track.Artist);

}

            }

      }

}

You can’t just use foreach because Tracks doesn’t expose an iEnumerator. It would be great if iTunes directly exposed managed interfaces. In that case, you could write something like:

iTunesApp app = new iTunesAppClass();

foreach(Track currTrack in app.LibraryPlayList.Tracks)

{

Console.WriteLine("{0} by {1}", track.Name, track.Artist);

}

In comparison, on the Mac OS, iTunes is scripted/automated using AppleScript. This is an English-like scripting language. Here’s what the similar code would look like:

tell application "iTunes"
repeat with currTrack in every track in the current playlist
log name of currTrack & " by " & artist of currTrack
end repeat
end
tell

Very simple! However, accessing the same data from C/C++/Objective C is much more difficult (maybe Cocoa has some nice wrappers I don’t know about…).

Now if only the play/stop/prev track/next track buttons on my Inspiron 8600 were programmable, I could hook them up to control iTunes. Has anyone hacked them?