MacDevCenter    
 Published on MacDevCenter (http://www.macdevcenter.com/)
 See this if you're having trouble printing code examples


Grabbing iTMS Preview Tracks the Geek Way

by Erica Sadun
05/09/2006

Have you ever tried to copy a preview track from the iTunes Music Store onto your iPod? I'll give you a hint: you can't. iTunes won't add those 30-second free previews of audio and video. Drag those previews onto the iPod playlist all you want. Ain't gonna happen. Unless you think different. In this article, you'll discover how. Here's a twisty, backdoor way of getting the job done by asking the store directly for the preview files from the command line, as if you were the iTunes browser itself.

Why Copy?

So why would you even want to copy a preview file onto your iPod? Here's one reason. There are many great iTunes Music Store tracks under thirty seconds in length. When you listen to the previews for these short tracks, you're essentially listening to the entire track for free. Which is one reason you might want a copy. Some are novel, delightful, or just strange. Others are extremely lame to say the least.

Another reason is that you may want to hear the preview as it sounds on your iPod. Computer playback doesn't offer the same acoustical experience. You may want to take the preview for a real test drive, kicking its aural tires before you plunk down your money. You're not going to get that experience unless you somehow copy the preview.

Finally, you may just be a geek. You may want to copy music or video previews to your iPod just to show that you can. Never overlook the sheer thrill of geek accomplishment, of the "oh, so that's how to do it" satisfaction.

Getting Started

1. The first thing you need to do is to create a playlist for your preview tracks. Add a new playlist, name it, and drag items from the music store onto that playlist. This is different from adding songs to your cart. An Add Song button appears for every track you add in this way. Also remember, you will download the free previews--you are not purchasing the songs or generally downloading the entire track.

figure 1

Fig. 1. Unpurchased tracks appear in your playlist with the Add Song button.

2. After setting up your playlist, Control-click (right-click) the playlist name. A contextual pop-up menu appears, allowing you to Open the playlist in a new window, Export Song List, Burn Playlist to Disc, Copy to Play Order, or Delete the playlist. Choose Export Song List. A Save dialog appears.

figure 2

Fig. 2. Choose Export Song List from the playlist's contextual pop-up menu.

3. This is important. In the Save dialog, make sure to choose Plain Text from the Format pop-up. (Other choices are Unicode and XML.) Specify a name for your listing and save the file to the Desktop.

figure 3

Fig. 3. Save your text in Plain Text format.

iPod & iTunes: The Missing Manual

Related Reading

iPod & iTunes: The Missing Manual
By J.D. Biersdorfer

4. Open your file in TextEdit. It may initially look like a mess, but search for those items that start with http://. Those are URLs and they lead directly to M4P (music) and M4V (video) files.

figure 4

Fig. 4. The URLs in the Playlist text file lead to audio and video previews.

5. (Optional) If you have a copy of Excel or another spreadsheet, you can open the playlist file to get a better view of the tabular data stored inside it. Choose File -> Open, select your file, and tell Excel's Text Wizard that you're using a tab-delimited text file. Note that track name and artist appear in the first, left-most two columns and the file URLs appear in the final, right-most column of your spreadsheet.

figure 5

Fig. 5. Excel makes it easy to view your playlist data in columns.

6. Now that you've found the URLs for the files, you can download them to disk. (The URLs start with http:// and end with either m4p or m4v.) I like using the curl command-line utility for this. Launch Terminal and type curl followed by the URL you want to download followed by the "save to" greater-than sign (>) followed by the name of the file you want to save it to. Curl retrieves the URL you provide and the ">" command tells Unix to save the results to your file.

figure 6

Fig. 6. Curl provides a simple-to-use command-line utility for retrieving data from a URL.

7. Add your new downloaded file to iTunes by dragging the file icon onto the iTunes library. iTunes adds the new file, using the name of the file you saved it to. iTunes will not automatically add the artist, album, or even the proper title. You must do all this by hand.

figure 7

Fig. 7. Drag the M4P or M4V file onto the iTunes library to add it to your media collection.

Please note that the M4P and M4V files you download are protected. You may play them in iTunes, in QuickTime, or on your iPod, but nowhere else.

figure 8

Fig. 8. iTunes Preview Files are protected.

Automation Tips

Now that you've seen how to manually download and add each song to iTunes, consider how much easier it would be to automate the process. Perl offers a great match to the challenges involved in the process. The steps you need to automate are: iterating through each track, locating the URL, downloading the data and naming the file, loading it to iTunes, and adding the proper metadata. Here are a few thoughts about each of these challenges.

Iterating Through the Tracks

The Preview text playlist created by iTunes consists of a header line with the categories for each column (Name, Artist, Composer, etc.) followed by one line per track. You can easily read in the track list and split it into individual lines by looking for the new line delimiter. This lets you create a foreach loop that iterates through the lines of the playlist file and processes each line that contains a URL.

#! /usr/bin/perl
# Fetch Preview Files from Playlist

use warnings;
use strict;

if ($#ARGV < 0) {die "Usage: $0 filename\n";}

# Read Playlist Text (Save as Plain Text!)
my $intext = "";
open(XFILE, $ARGV[0]);
while (<XFILE>)
{
  $_ =~ tr/\r/\n/;
  $intext .= $_;
}
close(XFILE);
my @playlist = split("\n", $intext);
foreach my $item (@playlist) 
{
  if ($item =~ /http/)
  {
      # Put the download & process parts here
  }
}

Locating the URL

Each line in the playlist file consists of 25 tab-delimited columns. The URL appears as the 25th item on each line. You can either split the line into fields (e.g., my @ilist = split('\t', $item);) and select the 25th item (i.e., $xurl = $ilist[24];), or you can just kill everything that appears before the start of the URL ($xurl =~ s/^.*http/http/;).

Downloading the Data and Naming the File

Once you've identified the URL of the file you want to retrieve, you can use any number of Perl libraries to download the data. I prefer to use the Unix curl command because it's universally available on Macs and doesn't require anyone to download and install CPAN Perl libraries. Here, I store the downloaded files in a folder named preview_files.

# Store recovered file to Desktop as DRM'ed m4p or m4v.
my $doit = qq{curl -s "$xurl" > ~/Desktop/preview_files/$xt.$xlast};
`$doit`;

Deciding how to name your files introduces something of a challenge. You can't use colons (":") and many other characters. Therefore I limit my names to characters and numbers taken from the actual name of the track. As you'll see, I do something similar (but adding spaces and parentheses) for the iTunes metadata.

# Create file name from the file extension and the track title
my $xlast = ($xurl =~ /m4v/)?"m4v":"m4p";
my $xt = $ilist[0];
$xt =~ s/[^A-Za-z0-9]*//g;

Loading to iTunes

I use osascript to automate application scripting. It's a handy way to control iApps from the command line. Here's how you can direct iTunes to create a new playlist. Always make sure to launch and/or activate an application before trying to send it directives.

# Activate iTunes and create a playlist named "iPreviews"
my $doit = qq{osascript -e 'tell application "iTunes" to launch'};
`$doit`;
$doit = qq{osascript -e 'tell application "iTunes" to set name of (make new playlist) to "iPreviews"'};
`$doit`;

Next, you need to add your new file to the iTunes playlist you just created. Here's the osascript call. Depending on how you've set up your iTunes preferences (iTunes Preferences -> Advanced -> General -> Copy files to iTunes Music folder when adding to library) this will either just add your new file to iTunes or copy it to the iTunes library.

# Add file to iTunes playlist
$doit = qq{osascript -e 'tell application "iTunes" to add ((((path to desktop) as string) \& "preview_files:" \& "$xt.$xlast") as alias) to playlist "iPreviews"'};
`$doit`;

Adding the Proper Metadata

The final downloading step involves recovering the specific track information lost in the download process. You can re-add all 24 items (the 25th, the URL is not properly part of the track info), or you can select just those items that are important, such as the name, artist, album, and genre. Once again osascript comes to the rescue.

# Filter unwanted characters
$item =~ s/[^A-Za-z0-9 ()\t]*//g;
my @ilist = split('\t', $item);

# Add the info for the file.
my $xx = qq{$ilist[1]};
$doit = qq{osascript -e 'tell application "iTunes" to set artist of track $xt" of playlist "iPreviews" to "$xx"'};
`$doit`;
     
$xx = qq{$ilist[3]};
$doit = qq{osascript -e 'tell application "iTunes" to set album of track "$xt" of playlist "iPreviews" to "$xx"'};
`$doit`;

# Update Title
$xx = qq{$ilist[0]};
$doit = qq{osascript -e 'tell application "iTunes" to set name of track "$xt" of playlist "iPreviews" to "$xx"'};
`$doit`;

Download the Sample Code

You can grab a copy of the automated free preview download script here. As with any software I make public, caveat emptor. Use at your own risk. Please don't sue me. Also please note that I take no precautions regarding duplicate names. If you download three items named "Finale" or "Conclusion" or whatever, they will overwrite each other. To fix this, either edit the playlist text file by hand or rename the tracks in iTunes. iTunes is smart enough to retain the proper preview URL when you edit the track name, and the playlist text file will use the track name you select, such as "Finale 1," "Finale 2," and "Finale 3."

Erica Sadun has written, co-written, and contributed to almost two dozen books about technology, particularly in the areas of programming, digital video, and digital photography.


Return to the Mac DevCenter

Copyright © 2009 O'Reilly Media, Inc.