Introduction
This is a simple example showing how to interact with ITunes version 6. The sample shows how to connect to Itunes version 6 using C# and how to get the list of songs in the itunes library or in the saved playlists.
The project was built in VS 2005. A reference to the COM object ITunes 1.6 needs to be added to your project. You can get the itunes SDK from here. The help file included in the zip was fairly useful.
Digging around on the internet, I found this site which helped me get started on this little project.
Using the code
I think the comments within the code are self explanatory:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTunesLib;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
iTunesApp itunes = new iTunesLib.iTunesApp();
private void Form1_Load(object sender, EventArgs e)
{
IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
{
comboBox1.Items.Add(pl.Name);
}
GetTracks((IITPlaylist)mainLibrary);
dataGridView1.DataSource = dataTable1;
}
private void GetTracks(IITPlaylist playlist)
{
long totalfilesize = 0;
dataTable1.Rows.Clear();
IITTrackCollection tracks = playlist.Tracks;
int numTracks = tracks.Count;
for (int currTrackIndex = 1;
currTrackIndex <= numTracks; currTrackIndex++)
{
DataRow drnew = dataTable1.NewRow();
IITTrack currTrack = tracks[currTrackIndex];
drnew["artist"] = currTrack.Artist;
drnew["song name"] = currTrack.Name;
drnew["album"] = currTrack.Album;
drnew["genre"] = currTrack.Genre;
if (currTrack.Kind == ITTrackKind.ITTrackKindFile)
{
IITFileOrCDTrack file = (IITFileOrCDTrack)currTrack;
if (file.Location != null)
{
FileInfo fi = new FileInfo(file.Location);
if (fi.Exists)
{
drnew["FileLocation"] = file.Location;
totalfilesize += fi.Length;
}
else
drnew["FileLocation"] =
"not found " + file.Location;
}
}
dataTable1.Rows.Add(drnew);
}
lbl_numsongs.Text =
"number of songs: " + dataTable1.Rows.Count.ToString() +
", total file size: " +
(totalfilesize / 1024.00 / 1024.00).ToString("#,### mb");
}
private void comboBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
string playlist = comboBox1.SelectedItem.ToString();
foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
{
if (pl.Name == playlist)
{
GetTracks(pl);
break;
}
}
}
}
}
Hope you find this useful, any comments/feedback appreciated.