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

Posted on Sat 16 May 2009 in General

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!