Friday, July 17, 2009

Converting the iTunes Playlists into the M3U format

Once the playlists are displayed in the listbox, the user can select the playlists to be exported and then click the “Convert” button. Here’s the code that is triggered by the button click:

private void btnConvert_Click(object sender, EventArgs e)
{
 // check existence of psPath
 DirectoryInfo di = new DirectoryInfo(txtResultPath.Text+"\\");
 if (!di.Exists) {
     MessageBox.Show ("Path to write to does not exist", "Problem",
         MessageBoxButtons.OK,MessageBoxIcon.Error);
     return;
 }

 foreach (Playlist pl in lbPlaylists.SelectedItems)
 {
     WriteToFile(pl, Path.GetDirectoryName(txtResultPath.Text+"\\"));
 }

 MessageBox.Show("Playlists written","Info",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
After some checking for the existence of the path to write the playlists to (lines 4 to 9), the code loops through all the selected playlists and writes out each playlist to a file by calling the auxiliary function “WriteToFile”.

Here’s this method:

private void WriteToFile(Playlist pl, String psPath)
{
 //create the file - overwrite if necessary
 FileInfo fi = new FileInfo (Path.Combine (psPath, pl.name() + ".m3u"));
 StreamWriter fs = new StreamWriter(fi.Open(FileMode.Create));
 // write stuff
 foreach (String trackID in pl.getTrackIDs())
 {
     String trackLocation = _library.GetTrackLocation(trackID);

     // now remove the "local" part of the location
     int pos = trackLocation.IndexOf("/iTunes Music/");
     string newFileName = trackLocation.Substring(pos+13);
     newFileName = "//Marvin/musik" + newFileName;
     newFileName = newFileName.Replace("/", "\\");

     fs.WriteLine(newFileName);
 }
 fs.Close();
}
This could be a member of the Playlists, but I’ve decided to leave it in the Converter class in order not to introduce additional dependencies in the Playlist class. This way, all the Playlist and Library classes do is read the contents of the iTunes library. This way the Converter class does not have to deal with any XML. The code iterates through all the tracks in the playlist (through their IDs, line 7). The tracks are retrieved in the order that they are in the playlist file (which is implicitly the order of the tracks in the playlist). In the loop, the file location of the track is retrieved (line 9). This location is then stripped of the “local part” (the part up to and including “/iTunes Music/”, lines 12&13), then the path for my server is added (line 14) and some proper formatting is applied (line 15) so the new file path is usable by the TVersity media server. Each constructed filename is written out to the file. The next post describes the additional functionality in the library class in order to retrieve the required track information from the XML.

Main | Next

No comments:

Post a Comment