Automating/scripting iTunes on Windows

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:

variTunesApp = WScript.CreateObject("iTunes.Application");

varmainLibrary = iTunesApp.LibraryPlaylist;

vartracks = mainLibrary.Tracks;

vari;

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

{

varcurrTrack = 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]

staticvoidMain(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: