Section 8.1. Scripting iTunes


8.1. Scripting iTunes

Unless you've been living underwater for the past three years, you've probably heard of iTunes. It's Apple's free digital jukebox program, which ships with every Mac sold. And just in case you can't find iTunes on your Mac (it should be in your Applications folder), you can download the most recent versionfor freefrom www.apple.com/itunes/download/.

In fact, since the scripts in this chapter will work best with the most recent version of iTunes, you might as well download a new copy right now.

You can download iTunes for Windows, too, but only the Mac version supports AppleScript.

8.1.1. Playing Tracks

The simplest task that iTunes can performand the one you're most likely to use it foris playing music. But the fact is, AppleScript can do far more with iTunes playback than you can do yourself (playing only sections of songs, say, or skipping songs automatically). For that reason, it's a good idea to get acquainted with the play command; it'll be your best friend when you script iTunes.

You use the play command like this:

tell application "iTunes"     (* Substitute any song for TrackName. Substitute the name of any playlist        for PlaylistName, or just use "Library". *)     play track "TrackName" of playlist "PlaylistName" end tell

For example, if you've got U2's latest killer track, "Vertigo," here's how that script would look:

tell application "iTunes"     play track "Vertigo (Single Version)" of playlist "Library" end tell

One thing to remember is that if you're going to play a specific track, you need to place the entire track name in quotes; the same applies to the playlist name. On the other hand, if you simply want to play the first song that iTunes finds, just type this:

tell application "iTunes"     play end tell

A similar command, playpause, toggles whether the music is playing. Run it once, a song starts; run it twice, the music stops.

Now that you know the basics, you can start mixing things up a bit.

8.1.2. Rating Songs

In iTunes, ratings are what you use to specify your favorite songsand your not-so-favorite ones. Think of them like Favorites in Safari: they're there to let you set aside your most visited songs.

The thing is, ratings don't help much until you've set them. Sure, you could go through your 10,000-song Library and find your unrated songsit'll just take a month of your life.

If you'd rather let AppleScript take care of finding your unrated songs, though, the following script is just for you:

--Part 1: tell application "iTunes"     activate     set unratedSongs to every track of playlist "Library" whose rating is 0     --Part 2:     repeat with currentSong in unratedSongs         --Part 3:          play currentSong         --Part 4:          set currentName to the name of currentSong         set currentArtist to the artist of currentSong         --Part 5:         set newRating to the text returned of (display dialog ¬             "Current song: " & currentName & return & "Artist: " & ¬             currentArtist & return & "Enter your rating (1-5):" ¬             default answer 3)         --Part 6:         set newRating to (newRating * 20)         set the rating of currentSong to newRating     --Part 7:     end repeat     display dialog "All your songs are now rated." end tell

When you run the script, AppleScript opens iTunes and finds all your unrated songs. Then it plays each song, letting you rate it on a scale from 1 to 5 stars, just as you would if you were clicking the little rating stars in iTunes itself. Pretty slick, huh?

Here's how the magic works:

  • Part 1 finds every unrated song in your iTunes Library and places that list in the unratedSongs variable. In iTunes, songs are rated on a scale from 0 to 100, with each star taking a value of 20. So all your one-star songs have a rating of 20, two-star songs have a rating of 40, and five-star songs have a rating of 100, for example.

    In this script, your list, named unratedSongs, holds all your songs that have a rating of 0. In other words unratedSongs is a list of every song that hasn't been rated yet.

While it might seem strange, this 0 to 100 scale is pretty common in programming. When a programmer wants to rate, rank, or check the progress of something, she'll often use a scale of 0 to 100 percent. That's all that's going on here: your songs with a rank of 0 stars are at 0 percent, while songs with a 5-star rating are at 100 percent.

  • Part 2 starts a repeat loop, setting the currentSong variable to the next unrated song each time the repeat statement runs. This part is what makes sure your script goes through all the unrated songs, without skipping any.

  • Part 3 starts playing the current song. That way, you'll be able to hear the song you're rating.

  • Part 4 gets the name and artist of the currentSong and places them into the currentName and currentArtist variables. This information can come in handy if you've got several covers of the "Star Spangled Banner" in your Library, for example; by checking the song's name and artist, you won't have to guess which version you're currently listening to.

  • Part 5 displays a dialog box that shows you the name (currentName) and artist (currentArtist) of the currently playing song, and asks you to give the song a rating (Figure 8-1).

Figure 8-1. iTunes accepts ratings from one to five stars. Since it's difficult to input stars in a text field, though, this script just asks you to enter a number, which AppleScript then converts into a star count.


  • Part 6 multiplies the rating you entered by 20. As described in part 1, by multiplying the number you enter by 20, your script can command iTunes to set the correct rating for the song.

  • Part 7 marks the end of the repeat statement. Once every song has been processed, the script finally displays a dialog box to let you know.

Now run the script, and rate all your songs. Once finished, you can organize your Library by rating: Simply choose File New Smart Playlist (Option--N), and fill in the settings like Figure 8-2.

In iTunes, a smart playlist is a playlist that updates itself with songs that match certain criteria. It's like a smart album in iPhoto (Sidebar 7.1), just for music.

8.1.3. Skipping Tracks

OK, you like music, but enough is enough. You don't have to listen to all of Chameleon by Herbie Hancock to get the picture (er, sound). Instead, wouldn't it be convenient if you could listen to bite-sized, 10-second snippets of every song in your whole Library? That way, you could play a sampling of your Classical-heavy Library to your friends, for instance, without them getting bored out of their minds.

With a new script, this job is a piece of cake. Run the following in Script Editor, and sit back as your ears fill with song samples:

--Part 1: tell application "iTunes"     play     --Part 2:     repeat until the player state is stopped         --Part 3:         delay 10         --Part 4:         next track     end repeat end tell

Figure 8-2. Here's what you'd use to create a "Five Star Favorites" smart playlist. Then, when you selected this playlist from iTunes' left pane, you'd see a list of all the songs you've rated with five stars. (If you'd like, you can create an album for four-star tracks, tooor even a "Masochist Music" playlist for all your one-star hits.)


Here's how the parts break down:

  • Part 1 starts playing the first song in your iTunes Library.

  • Part 2 uses a special kind of statementrepeat untilthat keeps running until a condition is met.

    In this case, the repeat statement keeps running until iTunes's player state is stopped (in other words, iTunes isn't playing anything at that moment). Once the last song is played, iTunes's player state will be stoppedand therefore, the repeat statement will stop as well.

  • Part 3 holds up the script for 10 seconds. (That's the only thing the delay command is good for: pausing your script's next command.) By doing this, you assure that the song will have 10 full seconds to play.

  • Part 4 skips to the next song in your Library, looping back to part 2 afterward.

Now you can listen to your whole Library in a few hours, rather than a few days. And if you encounter a song that you want to play all of, simply click Cancel in the dialog box; iTunes continues playing the whole song.

8.1.4. Converting Song Files

When you buy a music CD, you're essentially buying a disc full of AIFF-formatted music files. Record companies can fit 80 minutes of music on a 700 MB CD because each minute of AIFF music takes up about 9 MB.

Of course, if you're from the era of floppy disks, you're probably thinking "9 MB? That's sinful! I couldn't even fit 9 MB on my Mac Classic's hard drive!"and you'd be right. Even today, in the era of 500 GB hard drives half the size of the latest Harry Potter book and 60 GB iPods that fit in your pocket, you can quickly fill up your computer if you use uncompressed (AIFF-format) music.

That's why iTunes supports a number of space-saving, compressed song formats. These formats let you fit up to 10 times as much music in the same amount of hard drive space, allowing you to store 10,000 compressed songs on your 40 GB iPod, for example, rather than only 1,000 uncompressed songs.

Gem in the Rough
Beeping

It's great to be able to play songs with iTunes, but sometimes you might just want your script to play back a quick noisea chirp, a squeak, or a ding, for exampleto get your attention. AppleScript provides the simple beep command for just this purpose:

display dialog ¬     "Do not click the OK button!" display dialog "I warned you!" display dialog "This is your last chance!" beep

When your script runs the beep command, it plays back the sound you've selected in the System Preferences Sound Sound Effects tab. You can even specify a number after the command, to tell AppleScript how many times to beep. Try this command as an April Fools prank on your boss's computer, for example:

beep 1000 --Beeps 1000 times

There are benevolent uses for beeps, too. For instance, you can create a simple metronome with AppleScript by having your computer beep at regular intervals:

display dialog ¬     "Welcome to the AppleScript Metronome" set bpm to the text returned of ¬     (display dialog ¬     "How many beats per minute?" ¬     default answer 60) set pauseBetweenBeeps to (60 / bpm) repeat     beep     delay pauseBetweenBeeps end repeat

That script calculates what fraction of a second it has to pause between beeps, and then just continues beeping. Since you don't specify any number of times after the repeat command, though, your Mac continues beeping foreveror at least until you press the Stop button in Script Editor.

If simply an auditory beep isn't enough for you, though, visit System Preferences Universal Access Hearing tab and turn on "Flash the screen whenever an alert sound occurs." Now, whenever a script runs the beep command, it'll flash the screen, tooperfect for a visual metronome.


Of course, you have to give up some sound quality in exchange for these smaller filesbut iTunes gives you a choice of formats, so you can choose the space/quality trade-off that you like best. To get started converting your music, just choose iTunes Preferences Importing, and look at the Import Using pop-up menu. You have five format possibilities to choose from, as shown in Table 8-1.

Table 8-1. iTunes audio formats

Format abbreviation

Full name

What is it?

How much smaller than AIFF?

AAC

Advanced Audio Codec

AAC is the newest really-small music format, where each minute of music takes up only about 1 MB of space. AAC's sound quality is quite goodalmost as good as a CDand that's why it's the format used by the iTunes Music Store.

About 10x smaller

AIFF

Audio Interchange File Format

As described on Section 8.1.4, AIFF is a space-hogging, uncompressed music format. When you hear people refer to "CD quality," this is the format they're talking about. (In fact, AIFF is the sound format used by commercial audio CDs.)

N/A

Apple Lossless

N/A

This is a new, proprietary format that Apple developed for music aficionados. As its name suggests, this format doesn't lose any of your music's quality. What it does lose, though, is about half of a song's file size.

About 2x smaller

MP3

MPEG Layer 3

This is the original really-small music format, developed by the Moving Pictures Experts Group (MPEG) for playing music on computers. MP3's size makes it perfect for storing on small hard drivesor even sharing over the Internet. And although MP3's quality isn't quite as good as AAC's, MP3 are supported by virtually every operating system in existence. (Plus, many modern CD players can play MP3 CDsmusic mixes you burn yourself, which can hold about 10 times as much music as normal audio CDs.)

About 10x smaller

WAV

Waveform Audio

Unless you're a Windows die-hard, avoid this format. WAV takes up just as much space as AIFF, but has no better sound quality. In fact, WAV's only advantageif you can call it thatis that it's the format of choice for Microsoft Windows audio files.

Not smaller at all


Once you pick a format that's small enough for your sound-quality tastes, you can drag a bunch of songs into your iTunes Library. Then, once iTunes has finished importing the songs, just select them and choose Advanced "Convert Selection to [Whatever format you chose]". In a few minutes, iTunes converts all your songs into the format you selected the Preferences window.

Once iTunes is done converting your music, you can delete the old, unconverted music files to save hard drive space.

There are a few downsides to this whole procedure, though. For one thing, your converted files end up buried deep inside your Home Music iTunes iTunes Music foldernot exactly the easiest place to access from the Finder (if you want to email a song to a friend, for example). For another thing, any songs you convert using this method end up with entries in your iTunes Librarya minor annoyance if you're the type who likes to keep your files organized in folders, not programs. Finally, the whole procedure is far too complicated; you shouldn't have to add songs to your Library and then convert them.

Thankfully, there's another choice. Using an AppleScript, you can convert your songs to a new format, move the song files to the desktop, and erase the songs' entries from your iTunes Library, automatically. It's a clean, simple alternative to paying big bucks for a commercial music-converting programor suffering through iTunes's infuriating multistep conversion process.

Your new script is a droplet, an icon to which you can drag and drop files (Section 7.3.3). Here's how you code it:

--Part 1: on run     display dialog "Drag files to this script to convert them with iTunes" end run --Part 2 on open selectedItems     tell application "iTunes"         set convertedTracks to (convert selectedItems)     end tell     --Part 3:     repeat with currentTrack in convertedTracks         tell application "iTunes"             set trackLocation to (location of currentTrack)             --Part 4:             delete currentTrack         end tell         --Part 5:         tell application "Finder"             move trackLocation to the desktop         end tell     end repeat end open

Here's how it works:

  • Part 1: The run handler defines what happens if you simply double-click this script in the Finder. In this case, AppleScript presents a dialog box telling you to drag files to the script instead.

  • Part 2: The open handler defines what happens if you drag and drop files onto the script's icon. In this script, you send iTunes the convert command, giving it a list of all the files you want to convert. iTunes automatically returns a list of the newly converted files; that list then goes into the convertedTracks variable.

iTunes not only supports converting music to other music formats, it also supports converting video to music formats. For example, if you drag almost any QuickTime movie onto this script, iTunes strips out the audio and converts the movie's soundtrack to your preferred sound format. It's a great way to extract the Led Zeppelin music from Cadillac commercialsor the hip-hop songs from iPod commercials.

  • Part 3: The repeat statement tells AppleScript to go through your newly converted files, one at a time. For each converted song, AppleScript sets the trackLocation variable to the place the song is stored on your hard drive. (You'll use this information later to move the song file to your desktop.)

  • Part 4: Using the delete command (Section 5.5), the script removes your converted song from iTunes's Library. Keep in mind, though, that this code doesn't remove the song file itself; it only removes the song's entry in iTunes.

  • Part 5: Like the script on Section 5.3.1.3, this part uses the move command, directed at the Finder. Here, move pulls the song file out of its original location (trackLocation) and places the file on the desktop for easy access.

This script does not erase your original audio files; it simply moves the newly converted files to the desktop.

Save this script as an Application (Section 2.2.2) to create a working droplet. Now, whenever you drag a few music files to the droplet's icon, they'll quickly be converted into your preferred music format and placed on your desktop. From there, you can email the song files to a friend, listen to them in a program besides iTunes (like QuickTime Player [Section 8.3]), or move the song files to a more convenient folder on your hard drive (like your Music folder, for example).



AppleScript. The Missing Manual
AppleScript: The Missing Manual
ISBN: 0596008503
EAN: 2147483647
Year: 2003
Pages: 150

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net