Use the iTunes API and C# to do spring cleaning on your music collection

I was somewhat of an early adopter when it came to digital music. Due to the inordinate amount of time spent sitting at the keyboard, the PC was, for a very long time, my primary music player of choice. I usually have a decent set of speakers or headphones hooked up to my PC and use that to listen both while I work, or when I’m doing other stuff in the vicinity of the PC. However swapping CDs and dragging them to work and back seemed rather pointless once I could easily rip CDs to digital formats and store it on the computer and nothing beats having ones whole library of music at ones fingertips.

For the longest time, Winamp was what I used to play music…then I bought an iPod. I love my iPod because now I can take my entire music collection with me wherever I go, including the car. The iPod, however, did more or less force me to change my PC music software from WinAmp to iTunes (yes, I know there are alternatives, including WinAmp plugins, that would have saved me having to switch, but I was curious enough about iTunes that it didn’t bother me too much).

The first problem I had after importing my library was that iTunes had no album art for well over half of what I had imported. However, I had the album art. I had created a ‘folder.jpg’ file with the album art for every album in my collection so that it would appear in the Windows Explorer thumbnail view for the associated folder. The problem is, iTunes doesn’t look at that, it looks at the the file for embedded art (in the ID3 tag).

Now, I could have gone through and manually associated the images via the iTunes GUI, but dammit, I’m a programmer and that’s just not how we roll!!

Faced with a repetitive task, I, like any lazy-assed programmer would, looked for an automation solution. I was pleasantly surprised to find out that the iTunes App has an API. It’s a COM API, which ain’t my favourite, but it’ll do. So, without further ado, here’s how I associated the ‘folder.jpg’ album art, with every one of my nearly 10,000 song files, in no time flat.

First, I created a simple Console App and added a reference to the ‘iTunesLib’ COM component. (If you have iTunes installed, it should appear on the “COM” tab of Visual Studio’s ‘References’ dialog as “iTunes 1.xx Type Library”):

adding a reference

The next thing we need is a connection to the app and a reference to the main library object. The Library is exposed as a specific type of playlist, we can use the following code for that:

private static IITPlaylist GetLibraryPlaylist()
{
    IITPlaylist libraryPlaylist = null;
    Console.WriteLine( "Connecting to iTunes App... " );
    IiTunes iTunes = new iTunesLib.iTunesAppClass();
    Console.WriteLine( "Getting library:" );
    iTunesLib.IITSource librarySource = null;
    foreach ( iTunesLib.IITSource source in iTunes.Sources )
    {
        if ( source.Kind == ITSourceKind.ITSourceKindLibrary )
        {
            librarySource = source;
            break;
        }
    }
    if ( librarySource != null )
    {
        foreach ( IITPlaylist pl in librarySource.Playlists )
        {
            if ( pl.Kind == ITPlaylistKind.ITPlaylistKindLibrary )
            {
                libraryPlaylist = pl;
                break;
            }
        }
    }
    return libraryPlaylist;
}

Now we can iterate over the tracks in the library and call a function to assign the artwork (defined below)

IITPlaylist libraryPlaylist = GetLibraryPlaylist(); 
if ( libraryPlaylist != null )
{
    Console.WriteLine( "Repairing Tracks... " );
    IITTrackCollection tracks = libraryPlaylist.Tracks;
    int i = 1;
    foreach ( IITFileOrCDTrack track in tracks )
    {
        Console.CursorLeft = 0;
        Console.Write( "Checking track {0} of {1}......", i, tracks.Count );
        SetTrackArt( track );
        i++;
    }
}

…and lastly, here’s the code to set the album artwork to the ‘folder.jpg’ file in the same folder as the track, if it exists

private static void SetTrackArt( IITFileOrCDTrack track )
{
    if ( track.Artwork.Count == 0 && !track.Podcast )
    {
        string fileLoc = System.IO.Path.GetDirectoryName( track.Location );
        string artPath = System.IO.Path.Combine( fileLoc, "folder.jpg" );
        if ( System.IO.File.Exists( artPath ) )
        {
            Console.WriteLine( "Adding art to {0}", track.Location );
            try
            {
                track.AddArtworkFromFile( artPath );
            }
            catch
            {
                Console.WriteLine( "FAILED!" );
            }
        }
    }
}

As you can probably imagine, once you’re iterating over your entire iTunes Library, there’s lots of stuff you can to do make cleaning up your metadata easier. Some of other stuff I’ve used the iTunes API for include:

  • Normalizing band names so everything matches and is correct. (e.g. “Beatles”, “Beetles”, “The Beatles” all become “The Beatles”)
  • Finding tracks with missing album or artist information and list them in a text file to peruse and deal with later.
  • Populate the “Album Artist” to match the “Artist” field.
  • Find tracks in the library that are missing from the disk and delete them from the library

Hope you found this useful!

This entry was posted on Saturday, May 16th, 2009 at 1:33 pm and is filed under General. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

4 Responses to “Use the iTunes API and C# to do spring cleaning on your music collection”

  1. AWD_Guy Says:

    Great news. Many of us have been looking for a fix for this glaring Apple oversight for ages.

    For us non-programmers, would you care to share the application?

    Was the result that your art was added to the Library and as artwork.jpg and AlbumArtSmall.jpg, embedded in the tags, or both?

    Hopefully it did not embed it in the tags. With a large collection, that adds significantly to storage.

  2. Peter Kelley Says:

    Is the API documented anywhere? I have a whole bunch of tracks that have changed file location that I don’t want to lose the ratings and playlist information for. I need to put the library XML information back into the library.

  3. Tamlin Says:

    From an even lazier programmer than you, thanks heaps.
    The folder.jpg -> iTunes artwork script was exactly what I was looking for.

    Cheers & Beers

  4. ta Says:

    Thanks for the code example.
    Do you also know, hot to grab a Cover from the iTues Music Store or Amazon Store?
    I ripped some Compilation Discs and i want a different cover for all the music stuff.

    Best regards, Ta