Click here to Skip to main content
Click here to Skip to main content

Accessing songs and playlists from ITunes using C#

By , 20 Dec 2005
 

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();
        }
        // initialize Itunes application connection
        iTunesApp itunes = new iTunesLib.iTunesApp();
        private void Form1_Load(object sender, EventArgs e)
        {
             // get main library playlist
             IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
             // get list of all playlists defined in 
             // Itunes and add them to the combobox
             foreach (IITPlaylist pl in itunes.LibrarySource.Playlists)
             {
                   comboBox1.Items.Add(pl.Name);
             }
             // get the tracks within the mainlibrary
             GetTracks((IITPlaylist)mainLibrary);
             // set the datagridview1 datasource to the datatable.
             dataGridView1.DataSource = dataTable1;
        }

        // getthe tracks from the the specified playlist
        private void GetTracks(IITPlaylist playlist)
        {
             long totalfilesize = 0;
             dataTable1.Rows.Clear();
             // get the collection of tracks from the playlist
             IITTrackCollection tracks = playlist.Tracks;
             int numTracks = tracks.Count;
             for (int currTrackIndex = 1; 
                 currTrackIndex <= numTracks; currTrackIndex++)             
             {
                  DataRow drnew = dataTable1.NewRow(); 
                  // get the track from the current tracklist                 
                  IITTrack currTrack = tracks[currTrackIndex];
                  drnew["artist"] = currTrack.Artist;
                  drnew["song name"] = currTrack.Name;
                  drnew["album"] = currTrack.Album;
                  drnew["genre"] = currTrack.Genre;
                  // if track is a fiile, then get the file 
                  // location on the drive. 
                  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)
          {
              // get list of tracks from selected playlist
              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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

yann bertaud
Web Developer
United States United States
Member
Employed for the last 15 years at Autodesk, in San Francisco, CA.
 
Currently senior Software Quality Engineer in Autodesk Media Entertainment Division working on 3ds max.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestioniTunes over NetworkmemberHumschi12 Jun '12 - 21:51 
Do you know if it would work over network too ?
QuestionTrouble adding tracks to a playmemberKombu19 Aug '11 - 9:24 
I'm trying to add tracks to a playlist and am having a great deal of trouble. My code is examining the entire iTunes library, looking for tracks that have a null file location. Those tracks should then be added to a playlist for resolution. The code below executes without an error, but the tracks do not show up in the playlist. I feel as though I'm missing something obvious in casting the IITTrack variable to an object.
 
Note: "fixList" is an IITUserPlaylist
 
Any thoughts?
 
for (int trackIndex = 1; trackIndex <= trackCount; trackIndex++)
{
 
IITTrack track = tracks[trackIndex];
 
if (track.Kind == ITTrackKind.ITTrackKindFile)
{
 
IITFileOrCDTrack file = (IITFileOrCDTrack)track;
if (file.Location == null)
{
Console.WriteLine(track.Name + "\t" + "{missing location}");
object otrack = new object();
//otrack = (object)track;
otrack = track;
fixList.AddTrack(ref otrack);
 
}
}
}
GeneralCom exceptionmemberMember 443375531 Aug '08 - 23:33 
hello
 
i m facing com exception fot this;
 

iTunesApp itunes = new iTunesLib.iTunesApp();
Retrieving the COM class factory for component with CLSID {DC0C2640-1415-4644-875C-6F4D769839BA} failed due to the following error: 80040154.
 
Plz helpe me out
Generalapi amazon for search iTunes songs artworksmemberlupin9829 May '08 - 13:44 
Hi, where hi can find the amazon api for search iTunes songs artworks??
QuestionWindows2000memberSunshine Always26 Feb '08 - 22:32 
hi,
can i use this on windows 2000?
and what do i need to install to be able to execute the exe?
 
thanks.
QuestionHow to get Smart Info and Smart Criteriamemberguangstat13 Aug '07 - 20:03 
would it be possible to get the Smart Info and Smart Criteria of the Smart Playlist? Do you know how or no anywhere with example code?
D'Oh! | :doh:
QuestionHow to get only tracks out of "MUSIC"memberahaudi18 Jul '07 - 7:09 

I tried oreto fach the tracks in "music" i found no possibility to sort out podcasts and Films and so on. Any suggestions on this.
 
some testcode.
iTunesL ib.IITTrackCollection trcol = this.Itunes.LibraryPlaylist.Search(textBox1.Text, iTunesLib.ITPlaylistSearchField.ITPlaylistSearchFieldAll);
for (int i = 1; i < trcol.Count; i++)
{
if (trcol[i].Kind == iTunesLib.ITTrackKind.ITTrackKindFile)
{
 
result.AppendLine(((iTunesLib.IITFileOrCDTrack)trcol[i]).Artist.ToString() + ((iTunesLib.IITFileOrCDTrack)trcol[i]).Name.ToString());
}

 
i only found
trcol[i].KindAsString == "MPEG-Audiodatei")
but this seem language dependent!
 
by the way. good job!

 
servus.
Alex

QuestionHow to get the music folder location of iTunes by iTunes SDK?memberpudding3327 Apr '07 - 16:44 
Hi all,
How to get the music folder location of iTunes by iTunes SDK?
In the Menu of "Edit->Preferences->Advanced->iTunes Music Folder Location",there is a path which store the music of iTunes.The path can be changed by users and its default path is "C:\Users\zs\Music\iTunes\iTunes Music" in Vista,"..MyMusic\iTunes\iTunes Music" in XP.I want to get this path by iTunes SDK using C#.
I have read this article and look for interfaces and methods in the SDK,but have found nothing about that.
I have this problem for a long time.Could you help me?
Thank you very much!
 
Email:pudding33@gmail.com
 

 
pudding33 is looking foward to you anwaer!
Generaladd playlists in itumesmembertrxrst23 Apr '07 - 4:44 
Is there a way i can programatically add playlists to itunes
GeneralSweet, possible to get the filepath of trackmembersalle7824 Mar '07 - 3:01 
Thanks!
I was just looking for a way to get the filepath of a track, didnt know it was possible to cast a track to IITFileOrCDTrack to get the location.
Generalstreaming track from iPod to PCmemberHalid Niyaz22 Aug '06 - 20:23 
Hi all,
Assume that a track that is in iPod is not in iTunes library(not in local machine also). Am using iTunes SDK to write my own app for streaming a track from iPod to PC. iTunes SDK provides API to play it directly thru iTunes. But can anyone tell me if iTunes is locally storing it somewhere while playing a track from iPod or does iTunes SDK exposes any API to do this? can I convert a track that is in iPod, say in protected AAC format to mp3 using iTunes SDK?
 
Halid Niyaz
Questionhow do you get at the artwork?memberhillscottc1 Jan '06 - 21:11 
Have you had luck getting at the Artwork of a track using the ITunes SDK? The help files are not clear.
Perhaps someone can suggest how to make the given sample work?
 
foreach (IITTrack itrack in playlist.Tracks)
{
string Artist = itrack.Artist;
string Name = itrack.Name;
string Album = itrack.Album;

System.Drawing.Image art = itrack.????????? // HOW?
}
 

AnswerRe: how do you get at the artwork?membertayspen5 Jan '06 - 14:32 
Well if by "get at" you mean download and put into iTunes. I deided i wanted to attempt this. I think i have most if it....
 
This is what i used...
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WindowsApplication1.Amazon;
using iTunesLib;
 
namespace WindowsApplication1
{
public partial class Form1 : Form
{
iTunesApp tunes = new iTunesApp();
 
public Form1()
{
InitializeComponent();
}
private void Begin()
{
IITLibraryPlaylist mainLibrary = tunes.LibraryPlaylist;
GetTracks((IITPlaylist)mainLibrary);
}
private void GetTracks(IITPlaylist playlist)
{
// get the collection of tracks from the playlist
IITTrackCollection tracks = playlist.Tracks;
int numTracks = tracks.Count;
progressBar1.Maximum = numTracks;
for (int currTrackIndex = 1; currTrackIndex <= numTracks; currTrackIndex++)
{
// get the track from the current tracklist
IITTrack currTrack = tracks[currTrackIndex];
// if track is a fiile, then get the file location on the drive.
GetArt(currTrack.Artist, currTrack.Album);
System.Threading.Thread.Sleep(1000);
//currTrack.AddArtworkFromFile("C:\\" + " " + ".jpg");
progressBar1.Value += 1;
Application.DoEvents();
}

}
private static void GetArt(string artistname,string albumtitle)
{
string request = artistname + " " + albumtitle;
 
KeywordRequest req = new KeywordRequest();
req.keyword = request;
req.devtag = "MyDevTag :)";
req.mode = "music";
req.type = "lite";
req.page = "1";
 
AmazonSearchService search = new AmazonSearchService();
 
try
{
ProductInfo productInfo = search.KeywordSearchRequest(req);
 
if (productInfo.Details.Length != 0)
{
string result;
result = productInfo.Details[0].ImageUrlLarge;
System.Net.WebClient c = new System.Net.WebClient();
c.DownloadFile(result, "C:\\" + albumtitle + ".jpg");
}
}
catch
{
//do nothing..
}
 
Application.DoEvents();
}
 
private void button1_Click(object sender, EventArgs e)
{
Begin();
}
}
}

 
This line right here is waht causing the problem.
 
currTrack.AddArtworkFromFile("C:\\" + currTrack.Album + ".jpg");
 
it does Download the art to the C:\ drive pretty flawlessly. But perhaps somebody could tell me why setting the artwork in itunes doest work? It sayst here is a COM error...
 

Thanks for any help!
 
-T
GeneralRe: how do you get at the artwork?memberscott.hill6 Jan '06 - 11:50 

Thanks! That was just what I needed.
 
Regarding Setting the Art in iTunes...yes, I get what you mean. If I stumble across an answer, I will post.
GeneralRe: how do you get at the artwork?membertayspen7 Jan '06 - 6:16 
Yes if you find a way to inject to whole library w/o that error please post Smile | :) . Thanks
 
-T
GeneralRe: how do you get at the artwork?membertayspen20 Jan '06 - 11:19 
How, is it oging on the above? Did you ever get it? I have been close but still always results in an eror
GeneralRe: how do you get at the artwork?memberyann bertaud20 Jan '06 - 16:14 
I havent had a chance to look into this myself. maybe I'll have some time next week.
 
I did find a shareware that does it. called IArt.
GeneralRe: how do you get at the artwork?membertayspen21 Jan '06 - 8:48 
Cool, i look forward to seeing what you can find. Yea i heard of iArt but just wanted to do it myself Smile | :) .
GeneralRe: how do you get at the artwork?memberDrew Noakes21 Jan '06 - 12:30 
i'd also love to hear about this... anyone know how it's done?
 
Drew Noakes
drewnoakes.com
GeneralRe: how do you get at the artwork?membertayspen27 Jan '06 - 0:49 
I have still not suceeded...has anybody?
GeneralRe: how do you get at the artwork?membertayspen6 Feb '06 - 17:09 
I have got it, it now does what i want, which is add the album art when nay song is played in iTunes. This is how i did it. First you add the playerchangeevent, this is raised when the song is changed in itunes.
 
tunes.OnPlayerPlayEvent += new _IiTunesEvents_OnPlayerPlayEventEventHandler(iTunes_OnPlayerPlayEvent);//Declare Event
 
Hereis what we do on the Event
 

private void iTunes_OnPlayerPlayEvent(object o)
{
string Album = tunes.CurrentTrack.Album.ToString(); //This is the album of current songthats playing
string Artist = tunes.CurrentTrack.Artist.ToString(); //Artist of current playing song
Thread.Sleep(2000);
if (tunes.CurrentTrack.Artwork.Count < 1)
{
GetArt(Artist, Album);
iTuensArtistlbl.Text = artist;//This is just UI stuff
iTunesAlbumlbl.Text = name; //this to
}
else
{
try
{
this.tunes.CurrentTrack.Artwork[1].SaveArtworkToFile(string.Concat(Application.StartupPath, "\\albumArt.jpg"));
FileStream fileStream = new FileStream(string.Concat(Application.StartupPath, "\\albumArt.jpg"), FileMode.Open, FileAccess.Read);
this.iTunesArtPic.SizeMode = PictureBoxSizeMode.StretchImage;
this.iTunesArtPic.Image = Image.FromStream(fileStream);
fileStream.Close();
Application.DoEvents();
//Thatocde attempts to display the art if the song already had it.
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}

 
And here is the get art method, you will need an amazon dev tag to use this.
 

public void GetArt(string artistname, string albumtitle)
{
string request = artistname + " " + albumtitle;
 
KeywordRequest req = new KeywordRequest();
req.keyword = request;
req.devtag = MyTag;
req.mode = "music";
req.type = "lite";
req.page = "1";
 
AmazonSearchService search = new AmazonSearchService();
 
try
{
ProductInfo productInfo = search.KeywordSearchRequest(req);
 
if (productInfo.Details.Length != 0)
{
string result;
result = productInfo.Details[0].ImageUrlLarge;
System.Net.WebClient c = new System.Net.WebClient();
System.Threading.Thread.Sleep(2000);
c.DownloadFile(result, "C:\\art.jpg");
tunes.CurrentTrack.AddArtworkFromFile("C:\\art.jpg");
Application.DoEvents();
File.Delete("C:\\art.jpg");
}
}
catch
{
// Amazon seems to throw this exception even if the only problem
// is that keyword request returned no result, so simply do nothing..
}
 
Application.DoEvents();
}

 
Pretty straight forward code...
 
I would like to improve this bypresenting a use with the list of albums and they check which ones they want and it gets all art for the whole album. Any Ideas?
 
This code was obvioulsy the basis, of the album art idea.
 
-T
 
-- modified at 23:10 Monday 6th February, 2006
GeneralNice...but....membertayspen24 Dec '05 - 11:10 
would it be possible to get the playlist of the ipod? Do you know how or no anywhere with example code?
GeneralRe: Nice...but....memberrobroe27 Dec '05 - 23:00 
I think it is possible to get the playlists from the iPod, but what is your reason for doing this as the playlists on iTunes are normally the same as those on the iPod unless you manually sync them?
 
There is good example code in the help file which is mentioned in this article but you could try something like this (the ipod needs to be mounted) :

iTunesApp itunes = new iTunesLib.iTunesApp();
 
IITSourceCollection sources = itunes.Sources;
 
//Find the iPod source (where "iPod" is the name of your iPod)
IITSource iPod = sources.get_ItemByName("iPod");
 
foreach (IITPlaylist pl in iPod.Playlists)
{
//do something
}

This is the bare bones and needs error handling etc... The iPod is also a special type of source (IITIPodSource) which derives from IITSource so you may want to cast it to this so that you can get the additional functionality.
 
-- modified at 5:00 Wednesday 28th December, 2005
GeneralRe: Nice...but....membertayspen28 Dec '05 - 5:45 
Ok, Thanks so i modified the code a little to show the songs on the iPod. and only the songs on the iPod. Though it still show all the playlists, you can only acess songs on iPod. Here is that code.


iTunesApp itunes = new iTunesLib.iTunesApp();
 
IITSourceCollection sources = itunes.Sources;
 
//Find the iPod source (where "iPod" is the name of your iPod)
IITSource iPod = sources.get_ItemByName(iPodHelper.iPodName);
 
foreach (IITPlaylist pl in iPod.Playlists)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = pl.Name;
ListView2.Items.Add(lvi);
foreach (iTunesLib.IITTrack tempLoopVar_trk in pl.Tracks)
{
trk = tempLoopVar_trk;
DisplayTrack(ref trk, ref lvPlaylistSongs);
}
}

 


 
protected void DisplayTrack(ref iTunesLib.IITTrack track, ref ListView lv)
{
//title artist album length rating [index]
Graphics gfx = CreateGraphics();
ListViewItem lvi = new ListViewItem();
int colW;
SizeF colSF;
 
lvi.Text = track.Name;
colW = lv.Columns[0].Width;
colSF = gfx.MeasureString(track.Name, lv.Font);
if (colW < colSF.Width)
{
lv.Columns[0].Width = (int)(colSF.Width);
}
 
lvi.SubItems.Add(track.Artist);
colW = lv.Columns[1].Width;
colSF = gfx.MeasureString(track.Artist, lv.Font);
if (colW < colSF.Width)
{
lv.Columns[1].Width = (int)(colSF.Width);
}
 
lvi.SubItems.Add(track.Album);
colW = lv.Columns[2].Width;
colSF = gfx.MeasureString(track.Album, lv.Font);
if (colW < colSF.Width)
{
lv.Columns[2].Width = (int)(colSF.Width);
}
 
lvi.SubItems.Add(track.Time);
lvi.SubItems.Add(track.Rating.ToString());
lvi.SubItems.Add(track.Index.ToString());
 
lv.Items.Add(lvi);
 
}

 
Now my question is using the info we can get from each track would it be possible to copy the songs off the iPod? Do you know a way of doing this?
 

Thanks
 
-T
 

 

 
-- modified at 12:38 Wednesday 28th December, 2005
GeneralRe: Nice...but....memberNeil Lamka28 Dec '05 - 7:57 
Just searching around I found the following by Matthew David "Hacking Your iPod: Building Windows Solutions to Load Content onto Your iPod and iTunes" at http://www.informit.com/articles/article.asp?p=375499 that you might find of interest.
 
Neil Lamka
neil@meetingworks.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 21 Dec 2005
Article Copyright 2005 by yann bertaud
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid