Published on O'Reilly (http://oreilly.com/)
 See this if you're having trouble printing code examples

Editor's note: Hadley Stern, author of iPod and iTunes Hacks, has chosen five useful hacks to help you push the envelope of your iPod's capabilities. Your favorite toy just got better; learn how to turn your iPod into a universal remote, install it in your car permanently, and run Linux on it. In addition, make smart playlists and tame iTunes with AppleScript.


hack #9Turn Your iPod into a Universal Remote

Use a Pocket PC to record the “sounds” an infrared remote makes, transfer them to your iPod, and start changing channels with your new universal remote control.

We’re going to take an iPod and turn it into a universal infrared (IR) remote control, which can be used to control all your home electronic equipment, or just about anything that uses a remote control. For example, in my home, my iPod controls my TV, DVD player, Direct TV, Ultimate TV PVR, Media Center PC, Xbox, XM Satellite Radio, Roomba, and a few other random things, such as a robot. Figure 1-14 shows a variety of remotes your iPod can replace.

To do this, we are going to “record” the “sounds” an infrared remote makes on a PC and then put them on an iPod as songs. Adding a special sound-to- IR converter then turns those sounds back to IR and allows you to use your iPod as a remote control. As an added bonus, it works from up to 100 feet away. It’s a slick all-in-one unit, and you’ll never go back to using multiple remotes again.

Here’s what you’ll need for this hack:

Figure 1-14. One iPod to control a collection of remotes
Figure 1-14. One iPod to control a collection of remotes

Getting the IR Signal

The most important element is the sound-to-IR converter from Griffin, shown in Figure 1-15. This device (and software) was meant to extend the range of Pocket PCs and add consumer IR capabilities. You are first going to use the Pocket PC software to input the IR signals from your remotes, convert these signals to sound files, and then use your iPod to play those sounds through the sound-to-IR converter to control your devices.

Figure 1-15. Griffin’s IR device
Figure 1-15. Griffin’s IR device

First, install the Total Remote software on your Pocket PC. Follow the instructions and start entering all the remotes you’ll ultimately want to use on your iPod. To keep this example simple, we’re going to begin by turning the TV on and off.

On the Pocket PC, choose Start ->Programs ->Total Remote. Then, choose Edit ->Start One-Shot Sampling, as shown in Figure 1-16. Pick the power button on the interface.

Figure 1-16. Sampling your remote
Figure 1-16. Sampling your remote

As shown in Figure 1-17, Total Remote prompts you to hold the remote (in our example, the TV remote) up to the IR port on the Pocket PC. This records the IR signal.

Figure 1-17. Total Remote, prompting you to align your remote
Figure 1-17. Total Remote, prompting you to align your remote

Once you’ve captured the IR signal, you can test it by using the IR device included with Total Remote. After you verify that it works, it’s time to get that IR signal off the Pocket PC and onto a computer as a sound file.

Recording the Signal

Remove the Total Remote IR device from the Pocket PC headphone jack and run a line-out cable from the Pocket PC to the microphone or line-in port. You can get a 3.5 mm stereo audio cable such as this from Radio Shack or any computer store. Many computers come with one to run sound out to speakers; that’ll work too.

On your desktop computer (for our example, a PC, as shown in Figure 1-18), use a sound-editing program that can edit sounds and remove channels (left and right). This example uses SoundForge ($399.00).

Figure 1-18. Recording the sounds on a PC
Figure 1-18. Recording the sounds on a PC

In your recording application, set the recording format to the following (this is really important):

44 Hz, 16bit Stereo. PCM

We’re ultimately going to save the signal as a WAV (Windows sound file).

Press Record in the sound-recording application. Then, on the Pocket PC (with the line out from the headphone jack to the line in on the desktop computer), press the button to which you assigned the Power signal.

Stop the recording and press Play. If you recorded the signal properly, you’ll hear some weird beeps and pulses. That’s what the IR signal “sounds” like. In SoundForge, you can actually see the pulses and signal on a WAV graphic, as shown in Figure 1-19.

Figure 1-19. The pulses and signals in SoundForge
Figure 1-19. The pulses and signals in SoundForge

Next, highlight the right channel and mute it. If you skip this step, the sound won’t process through the IR device properly.

Now, save the sound recording as a 44 Hz, 16 bit Stereo, PCM WAV file. We called ours power.wav.

Putting the Signal on the iPod

Pop your iPod in the cradle. In iTunes, make a new playlist (I called mine TV) and then add the WAV file to the playlist, as shown in Figure 1-20.

The file transfers to the iPod, and we’re ready to test our new remote.

Figure 1-20. iTunes playlist with remote sound
Figure 1-20. iTunes playlist with remote sound

Ready, Aim, Fire

Remove the iPod from the cradle and put the Total Remote IR device in the iPod’s headphone jack, as shown in Figure 1-21.

Figure 1-21. iPod with Total Remote IR device
Figure 1-21. iPod with Total Remote IR device

Go to the playlist and point the iPod at the TV, as shown in Figure 1-22.

Figure 1-22. iTunes playlist with remote sound
Figure 1-22. iTunes playlist with remote sound

Click Play. If you’ve done everything right, your TV should turn on and off each time you play this sound. Go backhand input all your other devices. Congratulations! You can now control your TV—or anything else, for that matter—with your iPod.

—Phillip Torrone


Hack #11 Install Your iPod in Your Car, Permanently

Upgrade your car’s console to house the iPod and integrate the iPod with your car’s audio and electrical systems.

Sure, you can easily listen to your iPod in your car [Hack #5]. However, if you want to take your hacking skills to the next level, this hack gives you the knowledge you need to give your iPod the props it deserves by integrating it into your car’s interior. Once you’ve completed this hack, your iPod will have a permanent place in your car, integrated with the car’s electrical systems. Take a look at Figure 1-23 and get pumped up!

WARNING: This hack involves some dangerous chemicals and materials. Make sure you observe extreme caution and care when handling them.

Figure 1-23. An iPod integrated into the car’s console
Figure 1-23. An iPod integrated into the car’s console

Gathering the Supplies

Here’s a list of the materials you will need and where you can purchase them. Materials should cost you $400–$500:

CompUSA or the Apple Store

Alcone Theatrical Supply

Burman Industries


Fiber Optic Products

Local hardware store

Grocery store

Pep Boys Automotive (or a similar auto supply store)

Fabric store


Creating the Design

The first step in this process is a simple one. Look for the spot in your car that will best house your iPod, and then come up with a design.

TIP: Take into consideration that you will have a few wires to run, so make sure there will be room somewhere underneath.

I chose my center console, shown in Figure 1-24, simply because it was a large area with unused space and could be removed rather easily.

You can sketch out your concept, or simply dive right in with clay and start sculpting until you have the shape you want. I prefer to sketch first, but that’s not necessary. Begin roughing out your design in clay. Concentrate on the position of the iPod, and what will be most comfortable for you when operating it.

Once you have your basic shape in clay, you need to create a place for the iPod to sit (or lie), where it will connect to the charger. For this, you will need your actual iPod or iPod mini. Wrap your iPod with plastic wrap, completely covering it, and then tape it shut. Wrap tape around it a few more times, until you have about a 1/16" thickness. You need to do this to ensure that your iPod can slide freely in and out of whatever space you create for it in your final piece. Once you have cut out an area for the iPod to fit into, slide the iPod into the space, pushing gently to make an indentation in the clay.

igure 1-24. My center console before I started the project
Figure 1-24. My center console before I started the project

Make sure the walls around your iPod are fairly snug, but not so tight that it can’t be pulled out, as shown in Figure 1-25. Once you are satisfied, you can pull the iPod out of the clay, taking care not to destroy the enclosure you created.

Figure 1-25. Fitting the new enclosure for the second-generation iPod
Figure 1-25. Fitting the new enclosure for the second-generation iPod

TIP: The iPod is encased in plastic wrap and masking tape to ensure its protection, while at the same time creating a slightly larger space for easier insertion and removal of the iPod in the final casting.

Continue to fine-tune your sculpture, smoothing out and shaping the clay to fit your design. To ensure that your iPod fits in your final piece, slide the iPod into your enclosure every so often while you continue to sculpt. When you are satisfied with your creation, place your console on a large, flat board, making sure there is at least 5" from the edge of the console to the edge of the board on all sides. Rest the console on something flat to raise it up about half an inch from the board. You will need to build a wall completely surrounding it, and block off any sections that allow access underneath your sculpture to hold the silicone needed to take the mold of your sculpture.

Next, take a lump of clay and, using a rolling pin, roll out a large piece, keeping it about 1/4" thick. Cut this into strips, trimming off the ends. Repeat this until you have about 12 strips. Place the strips around the bottom of your console, pressing them firmly to lock the clay in place. The weight of the silicone will press against the clay, and any silicone that is able to leak around the clay and under your console will make it very hard to demold. Once all the sections on your console are blocked off with clay, cut your boards and place them around your console, leaving at least 1" around the perimeter of your console. The height of the boards must be at least 1" above the highest point of your sculpture or console. Lock the boards in place using the 2" screws, then take your silicone caulk and seal all the gaps and edges along the outside of your wall. Allow it to dry for 30 minutes.

Taking a Mold

You are now ready to take a mold of your creation. Using the mold release, spray your console and sculpture, making sure to cover every square inch. Now spray the insides of your walls and the board on which your console is sitting. Mix up the silicone using a one part A–to–one part B ratio. Don’t worry if you don’t make enough the first time; silicone will stick to itself, and you can always add another layer to fill up the mold if you need to. Pour in the silicone at the lowest point of your sculpture and let it rise on its own. This will help to fill in the small crevices and push out any trapped air. When the silicone is covering your sculpture by at least 1", you can stop and let it cure. The cure time for the Oomoo 25 silicone is 75 minutes, but cure times vary, so check the directions that came with yours if you did not purchase this type.

Now, you must build a two-part plaster support shell to hold the shape of your silicone mold. Begin by removing the screws holding the boards together. Pull gently but firmly to release the boards from the silicone. Coat the silicone with a thin layer of Vaseline, continuing down to the board on which your sculpture is lying. Now, take your burlap and cut it into strips. Make about 25 12" × 5" strips, 12 8" × 5" strips, and 6 6" × 3" strips. Fill your bucket with approximately four cups of lukewarm water, and begin adding your plaster. Add a little at a time, sifting it with your hands.

When you begin getting small white areas, or islands, you have added just about enough plaster. Add a little more, and then mix it up. You should have a pancake batter-like consistency. To make the first half of your shell, take one of the larger burlap strips and dip it into the plaster, fully submerging it. Pull it out and wring off some of the excess plaster. Now, fold it in half lengthwise and lay it on top of your silicone mold directly in the center, dividing the mold in half lengthwise, as shown in Figure 1-26.

Figure 1-26. The silicone mold with one half of its plaster support shell
Figure 1-26. The silicone mold with one half of its plaster support shell

Continue laying the strips down, going from one side of the mold to the other, until you have built a wall about 1" high. Then, begin laying more strips without folding them, until the left side of your mold is completely covered in about 2" of burlap strips. Let the plaster set up and dry. It will become very warm when it sets, so be careful not to touch it.

Once the plaster cools, begin brushing a thick coat of Vaseline all over the inside edge of your plaster shell, as shown in Figure 1-27. This prevents the next coat of plaster from sticking to the first, making the two halves easier to separate.

Now, repeat the burlap layering process, this time covering the right side to make the second half. Let the plaster set up and dry.

When the second half is cool to the touch, you can separate the two halves. Use a screwdriver to pry apart the plaster until it becomes loose enough to remove by hand. Be careful not to pull too hard and crack the shell. Set the two halves aside for now, as shown in Figure 1-28.

Figure 1-27. Brushing a layer of Vaseline on the first half of the plaster shell
Figure 1-27. Brushing a layer of Vaseline on the first half of the plaster shell

Figure 1-28. The plaster shell after it has been separated from the silicone mold
Figure 1-28. The plaster shell after it has been separated from the silicone mold

Removing the Mold

It is time to de-mold your sculpture. With the plaster shell removed, work your fingers carefully under the edges of the silicone until it comes loose from the bottom board. If necessary, use an X-acto knife to cut the silicone free from the board. Pickup the entire silicone mold and flip it upside down. Now you must peel the strips of clay from the silicone until you have access to your original console. Again, work your fingers around the edges of the silicone, prying it gently from your console. It should release very easily. Carefully pull the console from the silicone. You now have a perfect negative of your piece!

Cleaning out the mold is almost always necessary. You can simply take the mold outside and spray it down with a garden hose, but use a gentle setting, because a hard stream could damage the silicone. When the mold is completely dry, you need to place it back into its plaster shell. Place the silicone mold into one half of the plaster shell, making sure it is the correct half. Bring the other plaster half together with the first, closing it around the silicone. Strap the halves together with two large rubber mold bands. Your mold should look like Figure 1-29.

Figure 1-29. The silicone mold after it has been encased in its plaster support shell and bound with rubber mold bands
Figure 1-29. The silicone mold after it has been encased in its plaster support shell and bound with rubber mold bands

Spray the inside of the mold thoroughly with the universal mold release. Repeat to ensure proper coverage.

Coating with Plastic

Now, it’s time to pour in your first coat of plastic. The amount of plastic to mix depends on the size of your mold. The console I made took approximately 1 1/2 cups of plastic to cover the entire surface area with a thin layer.

Mix the plastic according to the directions, using equal parts of the A and B chemicals. Mix thoroughly and pour it in the mold. Pickup your mold and tilt it slowly from side to side, turning it around as you do to cover the entire surface area of the mold. Dump the excess into your mixing container, wait about 30 seconds, then pour it back in, repeating the process until the plastic begins to set up.

Wait about 30 minutes for the plastic to cure. Mix up about two more batches of plastic, repeating the last process and waiting 30 minutes between each coat. When the third coat is cured, mix up another batch of plastic, this time adding a filler to thicken it up, as shown in Figure 1-30. The filler helps to lighten the weight while adding density to the final casting.

Figure 1-30. A layer of thickened plastic being added to the mold
Figure 1-30. A layer of thickened plastic being added to the mold

Pour a cup of part A into your mixing container. Add a few spoonfuls of the URE-FIL filler, until the mixture becomes pasty. Add a cup of part B, and mix thoroughly. Pour it into your mold, turning and tilting it to fill in all the gaps and crevices until the mixture begins to harden. Wait 30 minutes.

Repeat this process two more times, waiting 30 minutes between each layer. You can add as many layers as you want, depending on the thickness you desire. After the last coat is cured, you can remove the piece from the silicone mold. Remove it gently, because silicone can tear if stretched too far. Your console should resemble Figure 1-31.

Figure 1-31. The final casting after being removed from the mold
Figure 1-31. The final casting after being removed from the mold

Sanding, Painting, and Cleaning Up

You must now trim and clean the edges of your piece, using a Dremel tool and sandpaper, as shown in Figure 1-32. A clean edge is important for a matching fit back into your car.

Figure 1-32. Using a Dremel tool to trim and sand the excess plastic from the edges of the casting
Figure 1-32. Using a Dremel tool to trim and sand the excess plastic from the edges of the casting

After the edges are clean, sand the piece until you achieve a smooth surface. Start with a coarse sandpaper, 80–100 grit, and work your way up to 300– 400 grit. If you are planning to back light a logo in your piece, you will need to sand down the area on the inside of your piece where your logo will be placed. This will allow the light to shine through. Be careful not to sand down too far! Use the Dremel tool to cut out a space for the dock connector to fit into where it will connect with your iPod, as shown in Figure 1-33.

Figure 1-33. Cutting an opening just large enough for your dock connector to fit into
Figure 1-33. Cutting an opening just large enough for your dock connector to fit into

Place the iPod where it will sit or lie, push the dock connector through the hole you made, and connect it to your iPod. Mix some dental acrylic and cover the backside of the connector to hold it in place. When it is hard, remove the iPod and mix up another small amount of the dental acrylic, using slightly more of the monomer for a thinned-down mix. Use an eyedropper to fill in the gap around the connector, as shown in Figure 1-34.

Let it harden, and then sand as needed. On either side of the connector, drill two small holes the size of the fiber-optic cable you will insert for lighting up that space, as shown in Figure 1-35.

Wipe down the piece with a damp cloth to remove excess dust. Before you start painting, you need to tape off the areas you don’t want to be painted. I chose to paint the enclosure where the iPod lies a glossy off-white. Tape up the connector if you choose to paint this area. After putting a few coats on that section and letting them dry completely, I taped off that whole section and applied the Apple logo sticker (to be removed later) so I could begin painting the rest of the console a light silver-gray to match my interior. Light-colored metallic car paint is slightly translucent, unless applied in numerous, heavy coats. I chose to use a darker metallic charcoal gray as a base color, and then paint over that with the lighter color. This also helped to block any light from coming through the area around the outside of the backlit Apple logo that I added.

Figure 1-34. Using dental acrylic to seal the dock connector in place
Figure 1-34. Using dental acrylic to seal the dock connector in place

Figure 1-35. Access holes for fiber-optic cable insertion
Figure 1-35. Access holes for fiber-optic cable insertion

After you’ve applied a few coats of paint, let it dry for about two hours, and then remove the tape and the Apple sticker. Cut a section of the foam rubber padding to fit the surface of the enclosure, so the iPod has a soft base to slide in and out on. Use spray adhesive to attach it. You can now add the lighting.

Cut off one of the cigarette-lighter adapter’s blue LEDs, and solder on a bright white LED in its place. The white LED is for the Apple logo, while the remaining blue one will be used to light the interior of the iPod’s enclosure. Make a separate enclosure for the white LED out of a spray paint can lid, to block any light from escaping through the sides of the console and at the same time direct it toward the Apple logo. Drill a hole in the center of the lid, and then use dental acrylic to hold it in place behind the logo. Insert the light into the hole in the center and tape it up. Then, take the fiber-optic cable and cut two pieces about two feet long. Push them into the small holes drilled next to the dock connector, and glue them in place. Turn them into the blue LED and tape them to it.

Hooking up the Electronics and Installing the Console

The final step in this process is to hookup all your electronics and install the console. Take all of your materials, the console, and any tools you will need into the car with you. First, you need to connect your dual-outlet cigarette lighter adapter, which can be purchased from your local auto supply store. This can be done a few different ways, but the easiest way for me was to just disconnect the wires from the existing dashboard lighter outlet and reconnect them to the outlet I’d purchased. Since I don’t smoke and I don’t use a cell phone, I really didn’t have any use for that outlet. Besides, many cars have an extra one on the passenger-side panel, down by the floor. If you find that you do need your outlet, you can purchase a separate lighter with a wiring kit to run off of the existing outlet. Connect the dual lighter adapter to the new outlet. You can now connect the car charger to one of them and your LED lighting to the other.

Connecting the iPod to your car stereo might pose a problem for some. Not all car stereos accept auxiliary input from an external source. Unfortunately, there is no way around this. You simply must have the correct type of stereo. Quite a few stereos now feature front-mounted RCA inputs, but you may have to purchase a separate adapter, as I did. If so, you’ll need an IP-Bus interconnector with left and right RCA inputs. The IP-Bus connects to the rear of the stereo and features two RCA jacks that protrude from the unit, allowing an external audio source (such as a CD changer or an iPod) to be connected. I chose to use the iCable, which is basically a stereo mini-jack that converts to dual RCA jacks. I plugged the stereo mini-jack into the Belkin car charger and ran the two RCAs to the adapter on the car stereo. The iPod is now connected directly to your car stereo (some car stereos require manually changing the menu to accept an auxiliary input). After double checking that everything is connected and functioning properly, attach the console and put the interior back together..

Figure 1-36. The final results
Figure 1-36. The final results

The Final Installation

Now that your new console is connected and functioning, enjoy it, but be very careful when driving! As beautiful as this installation might look(see Figures 1-36 and 1-37, don’t give your iPod more attention than the road

—Jesse Melchior


Hack #49 Run Linux on Your iPod

Turn your iPod into a Linux-running machine and write your own iPod applications.

Ever since the original iPod was released, users have come up with new and interesting ways to use their iPods as more than just MP3 players. Apple’s various updates have added to the firmware new features, such as calendars and contacts [Hack #33], games[Hack #36], HTML-like notes [Hack #39], and now photo storage capabilities [Hack #3].

Unfortunately, these new features can come only from Apple, so we are beholden to their timelines and commercial interests.

This is where Linux—or more specifically, uClinux (free)—comes to the rescue. uClinux is a special port of the Linux kernel that supports CPUs without a memory-management unit. Other than that, it’s basically a full-featured Linux kernel, including filesystem support for FAT32 and HFS+, TCP/IP networking, and Fire Wire, all with a nice Unix API.

By porting Linux to the iPod, we can create a freely available development platform where software can be developed for the iPod independently of the Apple firmware. What’s more, basing it on such an open system gives us immediate access to all the resources available on the Linux platform—that is, all those open source packages people use to build great software.


Installing Linux on your iPod consists of two basic steps: patching the iPod operating system stored on the hard drive, and installing a root filesystem for Linux. Installation is possible from Windows (using a third-party installer), Linux, or Mac OS X.

TIP: You must have root permissions to install Linux on your iPod.

Installation of Linux on your iPod is a nondestructive process and will leave all your existing configurations and music intact on your iPod. The included boot loader will also allow you to choose either the Apple or the Linux software to start at reset, so you can continue to enjoy the full-featured Apple firmware while you experiment with the Linux world.

Fire Wire/connection setup. To install Linux on your iPod, you first need to have your system configured for your iPod. If you are using Mac OS X, there is probably nothing further to do. However, if you are using Windows or Linux (especially if this is the first time!), you need to ensure that you have either Fire Wire or USB correctly configured for your iPod. To configure Fire Wire or USB for your system, consult the documentation provided with your operating system.

Once the operating system is configured, you need to determine how your operating system identifies your iPod. To do this, plug your iPod into your PC and ensure that it switches to Disk mode. Normally, it should do so automatically when the appropriate connection is established by your operating system; however, you can force entry into Disk mode by resetting your iPod (by holding down Menu and Play/Pause for three seconds) and then, when the Apple icon appears, holding down Fast-Forward and Rewind. Once in Disk mode, you should see the message “Do not disconnect” on your iPod. You should then check your operating system configuration to see how your iPod is configured.

TIP: This hack covers installing Linux on the iPod with a Linux based PC. If you want instructions for a Mac OS X or Windows machine, visit iPodLinux.com.

This hack works better with a Windows-formatted (FAT32) iPod. If your iPod is Mac-formatted (HFS+), it is generally easier to reformat it as FAT32 before you get started. See "Use Your iPod with a Mac and a PC" [Hack #35].

Locating your iPod. To locate your iPod under Linux, check the file /proc/scsi/scsi for an entry where the Vendor is Apple and the Model is iPod. For example:

  # cat /proc/scsi/scsi
  Attached devices:
  Host: scsi0 Channel: 00 Id: 00 Lun: 00
  Vendor: Apple Model: iPod Rev: 1.50
  Type: Direct-Access ANSI SCSI revision: 02

The scsi0 (Host) portion indicates that the iPod is the first SCSI device on your machine and so will be visible as /dev/sda. If on your system you see scsi1, your iPod will be visible as device /dev/sdb. The following example commands will use sda as the device address for the iPod. Please replace this with the correct device address for your configuration.

Backing up. Since we will update the partition information and replace the hard-drive firmware image, we will first make a backup of this data. Use the following commands to create the two necessary backup files:

  # dd if=/dev/sda of=ipod_boot_sector_backup count=1
  # dd if=/dev/sda1 of=ipod_os_partition_backup

The first backup file is simply a copy of the master boot record (MBR), which contains the partition table for the disk. The second backup file is a complete backup of the operating system partition on the iPod and includes the Apple iPod operating system (this file is 40 MB and can be compressed once the installation process is complete). Should you need to restore these backups for any reason, simply use the following commands:

  # dd if=ipod_boot_sector_backup of=/dev/sda
  # dd if=ipod_os_partition_backup of=/dev/sda1

TIP: Note that if you want to upgrade the Apple firmware, you should first restore the iPod operating system backup.It is also possible to completely restore your iPod to its factory state by using the Restore program from Apple. This will restore the original operating system and standard partitioning to your iPod. Unfortunately, this means any settings or music will be erased and will have to be copied back to your iPod.

Partitioning. Now that the backups are done, we will add a new partition to the iPod to hold the root filesystem for Linux. This is required on Windows iPods, because Linux cannot use a FAT32 partition for its root filesystem.

The following commands describe a session with fdisk that deletes the existing firmware partition and then creates a new, smaller partition to hold the firmware. The additional space is then used to create a new partition, which we will format for use with Linux.

TIP: The output displayed in the following steps is correct for a 20-GB iPod. Some output will be different for different sized iPods; however, the values entered by the user remain the same.
  1. Start fdisk:

      # fdisk /dev/sda
      The number of cylinders for this disk is set to 2431.
      There is nothing wrong with that, but this is larger than 1024,
      and could in certain setups cause problems with:
      1) software that runs at boot time (e.g., old versions of LILO)
      2) booting and partitioning software from other OSs (e.g., DOS
      FDISK, OS/2 FDISK)
      Command (m for help):
  2. Delete the firmware partition:

      Command (m for help): d
      Partition number (1-4): 1
  3. Create a new primary partition with a length of 1 cylinder:

      Command (m for help): n
      Command action
      e extended
      p primary partition (1-4)
      Partition number (1-4): 1
      First cylinder (1-2431, default 1): 1
      Last cylinder or +size or +sizeM or +sizeK (1-5, default 5): 1
  4. Activate the first partition:

      Command (m for help): a
      Partition number (1-4): 1
  5. Set the partition type to Empty:

      Command (m for help): t
      Partition number (1-4): 1
      Hex code (type L to list codes): 0
  6. Create the third primary partition from the second to fifth cylinders:

      Command (m for help): n
      Command action
      e extended
      p primary partition (1-4)
      Partition number (1-4): 3
      First cylinder (1-2431, default 1): 2
      Last cylinder or +size or +sizeM or +sizeK (1-5, default 5): 5
  7. Review the changes. Note that this is for a 20-GB iPod; for other iPod versions, the sda2 partition size will vary.

      Command (m for help): p
      Disk /dev/sda: 20.0 GB, 20000268288 bytes
      255 heads, 63 sectors/track, 2431 cylinders
      Units = cylinders of 16065 * 512 = 8225280 bytes
      Device Boot Start End Blocks Id System
      /dev/sda1 * 1 1 8001 0 Empty
      /dev/sda2 * 6 2431 19486845 b Win95 FAT32
      /dev/sda3 2 5 32130 83 Linux
      Partition table entries are not in disk order
  8. If everything looks okay, write out the partition table:

      Command (m for help): w
  9. fdisk will now exit, and we can create the new filesystem:

      # mke2fs -j /dev/sda3
  10. Set the maximal mount count to never:

      # tune2fs -c 0 /dev/sda3
      tune2fs 1.34 (25-Jul-2003)
      Setting maximal mount count to -1

Kernel installation. To install the kernel, you need the iPod boot loader (ipodloader), a version of the iPod Linux kernel, and the iPod operating system backup created earlier in the backup process.

First, extract the ipodloader and iPod Linux kernel archives into a working directory and check for any last-minute release notes. In the following steps, the make_fw tool and loader.bin file are from the ipodloader distribution, and the iPod Linux kernel version is uclinux-2.4.24-ipod0.bin.

  1. Extract the Apple OS from the backup image:

      # make_fw -o apple_os.bin -e 0 ipod_os_partition_backup
  2. Create a new image including the Linux and Apple operating systems:

        # make_fw -o my_sw.bin -l uclinux-2.4.24-ipod0.bin -i apple_os.bin loader.bin
  3. Copy the new image (which is about 4–5 MB in size) back to your iPod:

        # dd if=my_sw.bin of=/dev/sda1
  4. Copy the kernel modules onto the iPod, noting that the directory /mnt/ipod must exist and should not be in use. The lib directory refers to the directory from the kernel release and contains the modules directory:

        # mount -t ext2 /dev/sda3 /mnt/tmp
        # cp -r lib /mnt/tmp
        # umount /mnt/tmp

Userland installation. The iPod Linux Userland contains the operating system tools and libraries (including the Podzilla and mp3 applications). This archive should be installed on the root partition of your iPod, created during the partitioning step in the previous section.

  1. Mount your iPod root partition:

        # mount -t ext2 /dev/sda3 /mnt/tmp
  2. Extract the root filesystem:

        # cd /mnt/tmp
        # tar zxf /tmp/ipod_fs_040403.tar.gz
  3. Update the root filesystem with the latest kernel modules:

        # tar zxf /tmp/uclinux-2.4.24-ipod0.tar.gz lib
  4. Unmount your iPod root partition:

        # umount /mnt/tmp

Finishing up. The current release contains a number of usability bugs that can be resolved by executing the following commands:

  1. Mount your iPod root partition:

        # mount -t ext2 /dev/sda3 /mnt/tmp
  2. Perform fixes for /etc/rc. Replace /mnt/tmp/etc/rc with the following:

        hostname ipod
        mount -t proc proc /proc
        ln -s /dev/pty/m0 /dev/ptyp0
        ln -s /dev/pty/m1 /dev/ptyp1
        ln -s /dev/ide/host0/bus0/target0/lun0/disc /dev/hda
        ln -s /dev/ide/host0/bus0/target0/lun0/part2 /dev/hda2
        ln -s /dev/ide/host0/bus0/target0/lun0/part3 /dev/hda3
        ln -s /dev/tts/1 /dev/ttyS1
        mknod /dev/ttyp0 c 3 0
        mknod /dev/ttyp1 c 3 0
        modprobe tsb43aa82
        modprobe eth1394
        ifconfig eth0 mtu 170
        mount -t vfat -o ro /dev/hda2 /mnt
        mount -o remount,rw /
        hdparm -S 3 /dev/hda
  3. Perform fixes for /etc/inittab. Replace /mnt/tmp/etc/inittab with the following:

  4. Unmount your iPod root partition:

    	# umount /mnt/tmp
  5. Eject your iPod. The following command will unload the Fire Wire driver for your iPod. Once unloaded, your iPod will either reboot automatically or display the “OK to disconnect” message.

        # modprobe -r sbp2
  6. If your iPod did not automatically reboot, hold down the Menu and Play/Pause buttons for three seconds to reboot it.

Starting Linux on the iPod

Using the configuration in the previous section, your iPod will automatically start Linux on reboot. You should see the Tux logo, as shown in Figure 3-34, and then the normal Linux boot console messages will scroll by.

Once the operating system is booted, the Podzilla application will start, as shown in Figure 3-35. This work-in-progress interface mimics the Apple interface.

When you are finished with Linux, you can reboot the iPod by holding down the Menu and Play/Pause buttons for three seconds. When the Apple logo appears, hold down the Rewind button to start the Apple firmware.

To completely remove Linux from your iPod, restore the original firmware partition from your backup:

  # dd if=ipod_firmware_partition_backup of=/dev/sda1

Writing Your Own Applications

To develop applications for your iPod running Linux, you’ll need to use a special compiler that targets the ARM processor, because this is the instruction set used by the CPU on the iPod. You can download this for either Mac OS X or Linux from iPodLinux.com.

This compiler includes a special flag to generate binaries that will run on uClinux, so when compiling, you need to ensure it is used. Normally, you

Figure 3-35. The Podzilla interface
Figure 3-34. A Linux iPod on boot up

Figure 3-35. The Podzilla interface
Figure 3-35. The Podzilla interface

would use the LDFLAGS variable in your Make file to set this flag. The source package for Podzilla has an example of this:


So, to create a simple “hello world” application, use the following files:

  #include <stdio.h>
  int main(int argc, char **argv)
  printf("Hello world!\n");
  return 0;
  }  Make file
  hello: hello.o
          $(CC) $(LDFLAGS) -o hello hello.o 

To install this application, simply copy it to the root filesystem on your iPod and set the executable bit. To execute it during the boot up of the iPod, you can modify the /etc/rc file; just indicate the full path to your executable.

To develop graphic applications, use the Microwindows library (free), which provides a free set of primitives for developing graphical applications. Included are: ipodloader; iPod Linux Kernel; and iPod Linux root filesystem.

Hacking the Hack

There is now an active community working on developing applications for the iPod and providing assistance to newcomers. Different people have different interests, from games (see Figure 3-36), text editors, and new codec support to speech synthesis; all are possible with the Linux kernel.

Figure 3-36. Tetris on the iPod?!
Figure 3-36. Tetris on the iPod?!

In addition to these user applications, core support for iPod features such as voice recording and Fire Wire disk support is also being improved to further extend the possibilities. Use this hack as a springboard from your Linux on iPod imagination. Just as with Apple, with Linux on the iPod, you can write any number of applications for the iPod.

—Bernard Leach


Hack #58 Make Your Playlists Smart

Take your playlists to the next level by mastering Smart Playlists.

Smart Playlists are a powerful and underused feature in iTunes. These special playlists are updated automatically, depending on a simple set of criteria. The ability to create playlists by mixing music tracks from different albums and genres has always been one of the great features of iTunes, and Smart Playlists take this to the next level.

Introduced in iTunes 3, Smart Playlists let you personalize your listening experience by creating music lists that automatically update based on user specified criteria such as My Rating, Last Played, Comment, and Play Count. Some attributes about a track that can be used as criteria for creating a Smart Playlist (such as Song Name) are static, while others (such as Play Count) are dynamically updated to reflect track status. Smart Playlists have something to offer every listener.

To rate songs on the iPod, press the center (wheel) button two times. The first time will put the wheel into jog mode, and the second into rating mode. Once there, you will see the stars on the screen. Spin the wheel to increase or decrease the star rating. Make sure that iTunes is set to one of the two automatic transfer modes in the iPod Options screen. Otherwise, you will not be able to easily transfer Play Counts, Ratings, and Play Dates back to iTunes.

The Smart Playlist dialog (shown in Figure 4-28) is accessed from the iTunes File menu and can be broken into three distinct areas: the Match Line, the Criteria Lines, and the Limiter Area. The Match Line determines how the criteria are evaluated. It will change contextually depending on the Criteria Lines. When multiple criteria are specified, the Match Line will display the any/all pop-up. Otherwise, there will be no pop-up in this area.

Figure 4-28. The Smart Playlist dialog
Figure 4-28. The Smart Playlist dialog

Start by making your selections from the pop-up menus in the Criteria Lines area, choosing the desired attributes, operators, and values. The Criteria Line initially displays only one line. Press the + button to add additional criteria lines. The Match Line settings will determine how the criteria are evaluated.

The real power of Smart Playlists comes from combining various rules. To add a rule, or Criteria Line, simply click the+ icon. There is virtually no limit to the number of Criteria Lines you can have. Each rule is interpreted as a Boolean operator, meaning that a match or true result will display the track, while a false result or non match will not display the track.

After you’ve chosen your criteria, the Limiter Area allows you to limit the number of results returned by the Smart Playlist.

Track Attributes

Understanding the meaning of the many track attributes is important to get the most out of Smart Playlists. Attributes are always examined on a partakes in iTunes, regardless of the source of the music (e.g., CD, iTunes Music Store download, or analog recording). The only attribute that groups CD tracks together is Album Name. Tracks can just as easily be grouped by Artist, Genre, Year, or Play Count. Figure 4-29 shows the iTunes drop-down menu listing the track attributes you can use for building Smart Playlists. Table 4-15 describes all the attributes.

Figure 4-29. Drop-down menu of the track attributes that can be used to build Smart
Figure 4-29. Drop-down menu of the track attributes that can be used to build Smart Playlists

Table 4-15. Track attributes
Attribute name Description
Album The album on which the track was released.
Artist The artist who recorded the track.
BPM Beats per minute, or tempo. This is a numerical value describing the number of musical beats in one minute. The value is not calculated by iTunes and is not included with songs purchased from the iTunes Music Store. It must be entered manually or calculated by a third-party application. Although it has a strange interface, the application Ask the DJ ($29; free trial version available) effectively calculates BPM. Once the BPM attribute is written to your tracks, you can create excellent workout playlists.
Bit Rate The number of kilobits per second (kbps) used to represent the track. The higher the bit rate, the higher the resulting audio quality and the larger the file size. Music files are typically 128 kbps or higher, while audio books and other spoken-word content are often 96 kbps or lower.
Comment A user-defined field, which means you can do whatever you want with it. This is a great place to put keywords or extra information about tracks. For example, you may record the source of music files in the Comment field (e.g., my CD collection, bought from iTunes Music Store, ripped from DAT tree, borrowed from girlfriend, sampler CD from club, promo, etc.).
Grouping Used to group multiple movements in single larger classical pieces. Many users have developed individualized schemes involving grouping, such as subcategorization by genre or specially featured performer.
Kind The audio file format. Current supported formats are AAC Audio File, Protected AAC Audio File, AIFF Audio File, Apple Lossless Audio File, Audible File, MPEG Audio File, MPEG Audio Stream, Playlist URL, and WAV Audio File.
Last Played iTunes records the date and time when you play a track. Note that this is written only after a song has completed playing, not when the player is skipped to the next song.
My Rating Rate your music collection by assigning 0–5 stars in iTunes or on an iPod (third-generation or dockable and newer).
Play Count A musical odometer: keeps track of how many times you listen to each song.
Playlist Includes or excludes tracks contained within other playlists (new in iTunes 4. 5). This parameter allows for nesting and extremely complex mixed-Boolean Smart Playlists.
Sample Rate Number of samples of a sound taken each second to represent a sound digitally. The more samples taken per second, the more accurate the digital representation of the sound can be. The sample rate for CD-quality audio is 44,100 samples per second. This sample rate can accurately reproduce audio frequencies up to 20,500 Hertz (cycles per second), covering the full range of human hearing.
Size File size in megabytes.
Song Name Name attribute of the track.
Time Total duration of the track.
Track Number Track number as assigned per album (e.g., 7 of 10).
Year Year of track release.

Additional Attributes

Now, we’re on to the final set of Smart Playlist attributes to consider when creating a Smart Playlist. These variables limit playlist size and are important for portable audio players, ease of viewing in iTunes, and building CDs.

Here are the attributes to consider for limiting your playlists:

Limit to 25 songs selected by random
This line allows you to limit the size of the playlist and choose how the selection is made.
Song limits create manageable lists, which can be scrolled through visually.
Minutes & Hours
Timed lists are great for creating CDs. Try limiting to 74 minutes for the perfect CD-sized playlist.
MB (megabytes) & GB (gigabytes)
File-size limitations are important for portable music players, such as the iPod. Why let iTunes randomly fill your iPod mini when you can create four different 1-GB Smart Playlists, tailored to your taste?
Selected by:
This pop-up menu specifies how the song selector sorts the list. Choices include Random, Album, Artists, Genre, Song Name, Highest Rating, Lowest Rating, Most Recently Played, Least Recently Played, Most Often Played, Least Often Played, Most Recently Added, and Least Recently Added.
Match only checked songs
This selector is handy for omitting tracks from playback by iTunes or iPod. Uncheck songs in the iTunes Library, and they won’t show up in the playlist. (Unchecked songs do not play in iTunes by default. They play only when double-clicked.) Try unchecking holiday songs, exceptionally long tracks, or other content that you don’t often access.
Live Updating
Checking this box will allow your Smart Playlists to update on the fly. It’s a good thing it’s checked by default, because if it’s unchecked you’ll need to manually refresh the list by selecting all the tracks and pressing the Delete key. All the examples given in the next section should have this box checked.

Smart Playlists

Let’s take a look at how the attributes can be used to build selection criteria for Smart Playlists. Create a new Smart Playlist by selecting New Smart Play-lists from the File menu in iTunes. Fill the criteria in the following sections into the resulting dialog box and click OK. The new playlists you create will appear in the Source column on the left side of the iTunes window.

Artist Name. Want all the songs by a particular artist or DJ gathered into a playlist? Create a Smart Playlist with the following attributes (iTunes will automatically suggest naming it by the Artist Name):

  Artist – contains – Artist Name

This will match all instances of the Artist Name, including those that feature other artists, remixes, and, quite often, covers.

Workout. These Smart Playlists are excellent to put on the iPod for use in the gym. Try creating a Smart Playlist for each of the following ranges (you may want to adjust them depending on your fitness level).

Warm up

  BPM – is in the range – 125 to 13
  Limit to 5 minutes selected by random


  BPM – is in the range – 136 to 140
  Limit to 5 minutes selected by random


  BPM – is in the range – 141 to 150
  Limit to 5 minutes selected by random

Repeat the Walk and Run playlists as many times as desired.

High School Tunes. Combining comment information with years and ratings can create excellent nostalgic playlists. Try this:

  Comment – contains – my CD collection
  Year – is in the range – start of high school to end of high school

Rockin’ in the Free World. So, what do you do if you want a general rock list? One approach might be to do this:

  Match – any – of the following conditions
  Genre – is – Hard Rock
  Genre – is – Indie Rock
  Genre – is – Progressive Rock
  Genre – is – Southern Rock
  Genre – is – Rockabilly
  Genre – is – Psychedelic Rock
  Genre – is – Latin Rock
  Genre – is – Rap Rock

But why not use a nested Smart Playlist and make life easier?

  Genre – contains – Rock
  Last Played – is not in the last – 1 day

Lose the Streams. To keep streaming stations and tracks out of shuffle-mode playlists, try this:

  Kind – is not – MPEG Audio Stream
  Kind – is not – Playlist

Fresh Mix. Ratings are one of the best attributes. If you’ve rated your songs and are tiring of hearing the same songs over and over, try this:

  My Rating – is greater than – 3 Stars
  Last Played – is not in the last – 2 weeks

Never Been Listened To. Weed out the songs you’ve never listened to with this list:

  Play Count – is – 0

Clean Tracks. The “Lose the Streams” playlist specifies a method for excluding streaming tracks. Prior to the introduction of the Playlist attribute, this exclusion criterion had to be added to each Smart Playlist where streaming tracks needed to be excluded. Now, we can create nested playlists to exclude undesirable tracks from multiple playlists.

Create a Smart Playlist called “Clean Tracks” to match any of the following conditions:

  Kind – is not – MPEG Audio Stream
  Kind – is not – Playlist
  Genre – does not contain – Christmas
  Genre – does not contain – Holiday
  Genre – does not contain – Audio Book
  Bit Rate – is greater than – 96kbps
  Time – is less than – 10 minutes
  Match checked songs only

Now, you can add the following line to any other Smart Playlist:

  Playlist – is – Clean Tracks

Setting the attribute in this way will apply the “Clean Tracks” logic with only one step, essentially nesting the logic and eliminating the need to apply all the attributes to additional Smart Playlists.

TIP: A word about mixed Boolean operators: iTunes does let you use mixed Boolean operators (AND/OR) to select parameters for Smart Playlists, but the choice appears only after you’ve added a second line of variables to the playlist. A small all/any pop-up menu will appear at the top, where “Match the following condition” is located, changing the line to read “Match any/all of the following conditions.”

Mixed all/any behavior was not possible using Smart Playlists until iTunes 4.5, when the Playlist track attribute was introduced. Using Playlist, it became possible to nest playlists and create complex selectors.

Live Hour. On the iTunes web site, Apple suggests using keywords to create a simple romantic Smart Playlist:

  Name – contains – love

Building on this concept, you can gather all live songs from your library and do a live hour (although if you are a big fan of the group Live and you don’t have any of their live recordings, you might want to add Artist – is not – Live):

  Match - any - of the following conditions
  Name – contains – live
  Album – contains – live
  Comments – contains – live
  Limit to – 1 hour – by random

Hacking the Hack

Smart Playlists revolutionized the way we play our music. Their introduction in iTunes changed not only the way we listen to music, but also the way we think about it. If you can imagine a Smart Playlist, iTunes can build it for you and keep it fresh to boot.

If you’re a Mac user, getting the techniques of Smart Playlists under your belt now will make you much more productive as the feature is added to more and more Apple apps. It is no surprise to Smart Playlist users that

—David Bills


Hack #72 Tame iTunes with AppleScript Hack

Whether you need an AppleScript refresher or you are a willing AppleScript newbie, this hack provides the AppleScript basics you’ll need to understand the rest of the scripts in this chapter.

AppleScript is a simple but powerful programming language that lets you control applications on your computer and automate the tasks that they perform. Basically, an AppleScript script is a list of instructions. When you activate the script, the instructions are carried out. Additionally, a script is able to perform computations that allow it to make decisions about how its instructions are executed.

You write, test, and save AppleScript scripts with Script Editor, an application that comes installed with your Macintosh operating system. Scripts are saved as files and can be run like applications or, even simpler, like menu commands. As you will see, the language used to write AppleScript is much more English-like than other programming languages, which makes Apple- Script relatively easy to learn and use.

TIP: Unlike scripts written in other scripting languages (such as Perl or JavaScript) that can be written and saved using any text editor and can run on other computer platforms, Apple- Script scripts can be written only with an AppleScript editor and can be used only on a Mac. Apple provides Script Editor as part of the operating system, but there are a couple other script editors available as well—most notably, Script Debugger, a commercial product ($189.00; demo available), and Smile (free).

Using AppleScript, you can perform automated iTunes tasks that otherwise would be repetitive, time-consuming, or just plain difficult. For example, you can create scripts that clean up the text in track tags [Hack #74], create playlists [Hack #82], export artwork [Hack #86], send track tag information to other applications [Hack #80], [Hack #87], control the playing of tracks [Hack #88], send files to iPod [Hack #83], and much, much more.

TIP: This hack is a crash course in some of the AppleScript you should know to understand the hacks in this chapter. For a comprehensive guide to AppleScript, take a gander at AppleScript: The Definitive Guide, by Matt Neuburg (O’Reilly).

Writing AppleScript Scripts with Script Editor

Script Editor is located on your computer in /Applications/AppleScript. When you run Script Editor and create a new Script Editor document (File ->New) you might notice how similar it looks to a text editor (see Figure 5-1). As in a text editor, the document window is where you will enter and edit text that will eventually become a script.

The Script Editor toolbar contains a default set of four buttons:

Lets you start recording your actions in the Finder and any other Apple- Script-aware applications, although not all of these applications are

recordable (including iTunes). We will not be using this function much, if at all.

Figure 5-1. Script Editor is quite similar in appearance to a text editor such as TextEdit
Figure 5-1. Script Editor is quite similar in appearance to a text editor such as TextEdit

Stops execution of the script or halts recording if it is active. Pressing c-. (that’s the Command key and the period) also aborts the running of a script.
Executes the current script.
Tells Script Editor to check the script for correct syntax before running it. This does not check if the script actually works, just whether it’s constructed properly.

Along the bottom of the Script Editor window are three tabs that determine what is displayed in the lower half of the window. The Description tab contains a text description from the author of what the script does, displayable as a splash screen at startup. I also use it for temporarily parking snippets of code or copy-and-pasted text. The Result tab displays the last result computed by the running script. Event Log is a running display showing the results of a running script and logged results—very handy for debugging. You will use the Event Log window often while writing AppleScript scripts.

For the purposes of introduction, we’re going to create, save, and run a simple script to use with iTunes. We’ll get into more detail about the language momentarily.

Type the following text into the Script Editor window:

  tell application "iTunes"
  play playlist "Library"
  end tell
TIP: Hit the Return/Enter key on your keyboard to end each line and begin another. You will also notice that the continuation character (¬), created by pressing Option-Return, is used in many of the later scripts to segment single lines of code so that they look better in print; you can omit them in your code if you like.

Your Script Editor window should look like Figure 5-2.

Figure 5-2. An AppleScript script in the Script Editor window
Figure 5-2. An AppleScript script in the Script Editor window

When you first enter text into a Script Editor window, it's only text. But click the Compile button (or press Command-K), and Script Editor will check the script's syntax for any errors and format it nicely for you, as shown in Figure 5-3.

Figure 5-3. Script Editor, compiling and formatting the text
Figure 5-3. Script Editor, compiling and formatting the text

You now have a script that you can run and save.

To use a script from iTunes’s Scripts menu, you need to save it as a compiled script (see the sidebar “Save As…”).

A compiled script is one that has the proper syntax and whose commands work properly on your computer. However, it is not a freestanding application. It can be run only by Script Editor or within an application that has a Scripts menu and script interpreter (such as iTunes), or by using the optional system wide Scripts menu, installable by running the Install Script Menu AppleScript applet located in /Applications/AppleScript/. For this option, select Script from the File Format drop-down box in the Save As… dialog.

A script saved as an application is self-contained and can be run by double clicking it in the Finder, as with any other application. Sometimes, Apple- Script applications are called applets. Applets can also be activated from iTunes’s Scripts menu. For this option, select Application from the File Format drop-down box in the Save As… dialog.

A stay-open application is an AppleScript applet that just doesn’t quit—literally. In general, this is a type of script application that runs in the background indefinitely, watching for a particular condition or changes to a condition. For instance, a stay-open applet can be used to detect when a new track has started playing in iTunes and then perform some task. The script Current Track to iChat Status [Hack #87] is a stay-open applet. For this option, select Application from the File Format drop-down box in the Save As… dialog, and check the Stay Open checkbox.

Scripts can also be saved as text files in Script Editor. However, these text files can only be read by Script Editor, not by regular text editors. Script Editor doesn’t try to compile a script before saving it as text, so often it’s convenient to save an unfinished script this way. For this option, select Text from the File Format drop-down box in the Save As… dialog.

We will be working with compiled scripts at first. Later, you will see scripts saved as applets and stay-open applications.

  1. Select File ->Save As….
  2. In the Save As… box, enter the name for your script—Play Library is as good as anything else.
  3. Select either the non–user-specific /Library/iTunes/Scripts folder or the /Users/username/Library/iTunes/Scripts folder as the destination folder for your script (if either folder doesn’t exist, simply create it).
  4. Choose Compiled from the File Format menu, and click the Save button.

The script is available in the iTunes Scripts menu, as shown in Figure 5-4.

Go ahead and give it a whirl.

Figure 5-4. The Play Library script in the iTunes Scripts menu
Figure 5-4. The Play Library script in the iTunes Scripts menu

AppleScript for iTunes: A Primer

The language of AppleScript is pretty similar to everyday language (though with a stricter-than-English grammar), so you won’t have to learn too many new code words. This also makes it much easier to explain. Usually, a line of AppleScript does exactly what it says it will do.

tell statements. Type this fairly simple sentence into Script Editor, and then activate it by pressing the Run button:

  tell application "iTunes" to play

This is a tell statement; it tells a particular application to do something. In this case, it tells iTunes to start playing. tell statements contain objects and commands, which are very much like nouns and verbs, respectively. When you want to perform several commands on one targeted application, you can use just one tell statement around a block of other commands, terminated by an end tell:

  tell application "iTunes"
    set sound volume to 40
    set EQ enabled to true
  end tell

Sometimes, this is called a compound tell statement or a tell block. Usually, all of a script’s commands and computations occur within just one set of tell statements.

Objects and references. An AppleScript object is a thing that is scriptable. In the case of iTunes, this includes a playlist, a track, an audio source, and so on. AppleScript identifies an object in a scriptable application by using a reference to it. A reference is an unambiguous pointer to a very specific thing. Observe the middle line in the following script:

  tell application "iTunes"
    play track 7 of user playlist "Sparkle and Fade"
  end tell

In this script, the phrase track 7 of user playlist "Sparkle and Fade" is a reference to a specific track in a specific playlist in the application iTunes. The word of is used in a reference to unambiguously connect a particular object to its container; in the previous code snippet, the user playlist named “Sparkle and Fade” is the container of track number 7.

Additionally, an object can contain properties. For example, name is a property of the track object; the value of name is the text of the track’s Song Name. You can specify a particular property of an object using a reference as well. In the following script, the statement in the second line references the name of a particular track in a particular playlist:

  tell application "iTunes"
    name of track 7 of user playlist "Sparkle and Fade"
  end tell

Often, rather than typing the same reference over and over whenever you need it in the script, you can store the reference in a variable. A variable is a user-named holder for a value. The value in this case will be a reference. In the following example, I store a reference to the playlist called “Mom’s Favorites” in a variable I have chosen to name thisPlaylist:

  tell application "iTunes"
    set thisPlaylist to playlist "Mom's Favorites"
  end tell

Later in the script, whenever I want to refer to the playlist “Mom’s Favorites,” I can simply use the variable thisPlaylist instead.

get and set (and sometimes copy). You can retrieve the value of a variable or property with the AppleScript command get, and you can assign a new value to a variable or property with set:

  tell application "iTunes"
    -- get a value
    copy (get name of track 12 of playlist "Favorites") to trackName
    -- and set one
    set name of track 4 of playlist "Favorites" to "Everlong"
  end tell
TIP: In AppleScript, a line starting with a pair of dashes (--) is a comment, there for your own reference and the edification of others reading your code. The AppleScript interpreter ignores comments, so we encourage you to comment liberally.

The AppleScript copy command, which I used in the statement with get in the previous example, is similar to the set command. Notice that their syntax appears inverted. A set statement assigns a variable to a value:

  set thisVariable to someValue

whereas copy assigns a value to a variable:

  copy someValue to thisVariable

Because there are some situations in which their usages are not interchangeable (situations that are a bit too advanced to explain here) I got into the habit of using set exclusively. You should, too.

Conditionals. You can determine how the script will behave by testing whether certain conditions are met by way of a conditional statement. By far, the most common conditional across programming languages is the if...then statement—literally, “if the result of an expression is true, then do something.”

The following snippet of code tells iTunes to play if it is currently paused:

  tell application "iTunes"
    if player state is paused then play
    end tell

And this bit of code instructs iTunes to delete the “Black Sea” playlist if it is empty (literally, “if the number of tracks is zero”):

  tell application "iTunes"
    if (count tracks of playlist "Black Sea") is 0 then delete playlist "Black Sea"
  end tell

In much the same way that you can group together several statements in a tell block, you can also create compound conditional statements, causing all of the enclosed statements to be run if the if condition is true.

This code checks to see if the playlist "Mom's Favorites" is set to shuffle. If not (that is, if the statement shuffle of playlist “Mom‘s Favorites” is false is true), iTunes is instructed to turn on shuffling for “Mom’s Favorites” (i.e., set the shuffle property to true) and play it:

  tell application "iTunes"
    if shuffle of playlist "Mom's Favorites" is false then
      set shuffle of playlist "Mom's Favorites" to true
      play playlist "Mom's Favorites"
    end if
  end tell

A compound block ends with an end if statement.

TIP: Notice that the if...end if block is contained within the tell...end tell block. This is called nesting and is rather common practice in scripting logic.

You can also use else to provide an alternative task if the initial if condition is not true. Here, for example, if mute is not true (i.e., audio is not muted), go ahead and mute the sound now:

  tell application "iTunes"
    if mute is true then
      set mute to false
    else -- if mute is not true
      set mute to true
    end if
  end tell

The else terminates the initial if block in much the same manner an end if would, but further states that there’s an alternative coming up. The end if then closes the else block.

When an if statement offers an alternative using an else statement, the flow of the script is said to branch to either the if or the else clause.

You can offer more alternatives using else if:

  tell application "iTunes"
    if player state is paused then
    else if player state is playing then
    end if
  end tell

In this script, there are three possible branches. If neither of the conditions in the if or else if statements are true, then the final else clause is executed no matter what. You can use as many else if clauses as you require.

Repeat loops. A repeat loop iterates over a set of statements a certain number of times, on each item in a collection of objects, or while a certain condition is true. AppleScript provides repeat loops for each of these occasions.

In the course of the hacks in this chapter, we will most often be using a repeat loop to perform a set of tasks on each item in a list. A list, as the name suggests, is a collection of items (strings, numbers, object references, other lists, etc.) delimited by commas and held within braces, like so:

  -- text strings:
  {"Come Together", "Something", "Maxwell's Silver Hammer"}
  -- numbers:
  {1, 456, 27}
  -- references:
  {file track id 4100, file track id 4099, file track id 4098}
  -- combination:  {2,"cute to be",4,"got","ten"}

The lists you use in your interactions with iTunes usually contain track or playlist references.

To briefly illustrate how various repeat loops work, let’s suppose you want to change the artist’s name for every track in a playlist to Talking Heads. The first task is to get the list of tracks in the playlist. The following code sets a variable called theList to a list of references to every track in the “Talking Heads Songs” playlist:

  tell application "iTunes"
    set theList to every track in the playlist "Talking Heads Songs"
  end tell

Each track reference in theList is an item of that list. Now we can loop through each item in the following ways.

Here, each item in theList is assigned to the variable thisTrack on each loop:

  tell application "iTunes"
    set theList to every track in the playlist "Talking Heads Songs"
    repeat with thisTrack in theList
      set thisTrack's artist to "Talking Heads"
    end repeat
  end tell

Here, the variable i is automatically incremented on each loop and is used to target each item in the list successively:

  tell application "iTunes"
    set theList to every track in the playlist "Talking Heads Songs"
      repeat with i from 1 to (count items in theList)
        set artist of item i of theList to "Talking Heads"
      end repeat
  end tell

This repeat loop references the tracks in the playlist directly and does not use the list variable at all:

  tell application "iTunes"
    repeat with i from 1 to (count every track of playlist "Talking Heads Songs")
      name of track i of playlist "Talking Heads Songs"
    end repeat
  end tell

Many of the scripts in this book use variations of these repeat blocks. I provide greater detail when discussing a script that uses a repeat loop.

Consulting the dictionary. An application’s AppleScript Dictionary describes all the objects and commands that the application understands. It’s generally useful to take a look at the Dictionary before you start scripting. You can access iTunes’s AppleScript Dictionary, shown in Figure 5-5, in one of two ways: click on Open Dictionary in Script Editor’s File menu and select iTunes from the list of applications that appears, or drag the iTunes icon to Script Editor’s icon in the Finder or the Dock.

Figure 5-5. iTunes 4.5’s AppleScript Dictionary
Figure 5-5. iTunes 4.5’s AppleScript Dictionary

In Figure 5-5, the column on the left side of the window lists the various AppleScript classes (objects) and commands that iTunes understands. The track object is selected, and its properties are displayed in the right column.

Basic Debugging

No matter how well you know your AppleScript syntax, your script will generate errors while you are developing it and trying to get it to work properly. Script Editor has a couple features that will help you observe how a script is working so that you can see results, spot trouble, trap errors and problems, and eliminate a lot of the guesswork (although guesswork will always go on!).

You will want to be able to see the final results of any script actions, so click on the Result tab. You can resize this window so that you have easy visual access to it while working on your script in the main Script Editor window. The Result window always displays the last result from the Script window, as shown in Figure 5-6.

Figure 5-6. The Result window
Figure 5-6. The Result window

To see how a script is interpreted by AppleScript as it’s running, click the Event Log tab. When you run a script from Script Editor, the Event window (see Figure 5-7) will display each command as it’s interpreted by Apple- Script and each result (when available). This is particularly helpful in refining your syntax or figuring out where a bad script has gone wrong.

Figure 5-7. The Event window
Figure 5-7. The Event window

The iTunes Scripts menu

You need to put AppleScript script files for use with iTunes in a special folder so that they will be accessible from the iTunes Scripts menu.

To make iTunes scripts available to all users of your Mac, create a folder called Scripts in the /Library/iTunes folder.

To make iTunes scripts available only to a particular user of your Mac (most likely you), make a Scripts folder in that user’s personal /Library/iTunes folder (i.e., /Users/username/Library/iTunes, where username is the user’s login name).

After creating the Scripts folder, the next time you launch iTunes you will see the AppleScript menu bar icon appear magically between the Window and Help drop-down menus.

Compiled and application scripts in the Scripts folder will appear in iTunes’s Scripts menu. Scripts saved as an Application Bundle cannot be accessed via the iTunes Scripts menu. (We will be using and writing both compiled and application scripts.)

You can organize your scripts to some degree by placing them in folders inside your Scripts folder—one folder deep. You can also use aliases to scripts that are stored outside the Scripts folder. This might be helpful to you in the Finder, but the scripts will still appear in one long list in the iTunes Scripts menu.

Another trick for staying organized in the Scripts menu is to use various alphanumeric prefixes in your script names, such as spaces, underscores, bullets (Option-8), or degrees (Shift-Option-8). This groups like-prefixed scripts together by various alphanumeric strata in the Scripts menu. I am not aware of a maximum limit on the number of scripts you can put in your Scripts folder. I have had as many as 288, and no evil was visited upon me.

Alternatives to the iTunes Scripts menu

In addition to iTunes’Scripts menu, you can also use the system wide Scripts menu. This is handy for accessing iTunes scripts if iTunes is not the front most application. You add scripts to the Finder’s Scripts menu by putting them in /Library/Scripts (for all users) or /Users/username/Library/Scripts (for individual users). As with iTunes, once you create the folder, a drop-down menu with the AppleScript icon appears in the Finder menu bar.

TIP: If the Scripts menu was not installed with your system, download it for free from Apple at www.apple.com/applescript/scriptmenu. The installer should also be located in /Applications/AppleScript/. Simply run the Install Script Menu script located within that folder to install the system wide Script menu.

You can drag and drop AppleScript applets (scripts saved as self-contained applications) to the Finder’s toolbar for easy access.

Dock and launcher applications are handy for firing scripts, too. I use the venerable DragThing ($29.00; trial version available) to run compiled scripts.

There are also several applications that allow you to assign shortcut keys to AppleScript applets. These include iKey ($20.00; free trial version available) and QuicKeys ($99.95; trial version available).

Final Thoughts

You now have the basic tools for manipulating iTunes with AppleScript, and the scripts that lie ahead will reveal to you the range of tasks that you can accomplish with it. We will discuss each new concept as it comes.

—Doug Adams

Hadley Stern is a designer, writer, and photographer residing in Boston.

Copyright © 2009 O'Reilly Media, Inc.