Thursday, February 17, 2011

Traverse iTunes Music Library

In this post I want to show, how to traverse the complete iTunes music library or single playlists using C#.
The previous post is required for that (including iTunes in C#).
Now let iTunesPlayer again be an object of the type iTunesApp, referencing iTunes. Then the property iTunesPlayer.LibraryPlaylist.Tracks returns all media files loaded by iTunes as objects of type IITTrack.
The following sample code writes all titles to a textbox (which is textBox1, Multiline has to be true and Scrollbars enabled):

iTunesApp iTunesPlayer = new iTunesApp();
foreach (IITTrack track in iTunesPlayer.LibraryPlaylist.Tracks)
{
    textBox1.Text += track.Artist + " - " + track.Name + Environment.NewLine;
}

But also specific playlists can be addressed. With the property iTunesPlayer.LibrarySource.Playlists all playlists can be accessed. Every playlist again has the property Tracks, which contains the media files in it.
The following sample code output all playlits from iTunes with all their titles  (the first playlist is the complete library):

foreach (IITPlaylist playlist in iTunesPlayer.LibrarySource.Playlists)
{
    textBox1.Text += "Playlist: " + playlist.Name + Environment.NewLine + Environment.NewLine;
    foreach (IITTrack track in playlist.Tracks)
    {
        textBox1.Text += track.Artist + " - " + track.Name + Environment.NewLine;
    }
    textBox1.Text += "--------------" + Environment.NewLine + Environment.NewLine;
}

No comments:

Post a Comment