Rerating iTunes tracks on the fly

My usual iTunes playlist for office listening is a smart playlist that contains tracks with a rating of 3 stars or more that I haven’t listened to in at least a week. When I add new tracks to the library, I always give them 3 stars to start out so they get into that playlist. Some just don’t cut the mustard and need to be downgraded. Since the best time to downgrade a song is while I’m listening to it, and since I usually have iTunes hidden while I work, I wrote an AppleScript to do the downgrade and used FastScripts to bind it to the easily-remembered keystroke Control-Option-Command-downarrow. (It is easy to remember. First, almost all of my customized keystrokes use Control-Option-Command because I’ve never seen it used in an application and its easy to mash down those three adjacent keys simultaneously. And the downarrow is pretty obvious, isn’t it?)

Here’s the script:

1:  tell application "iTunes"
2:    set downTrack to current track
3:    next track
4:    set oldRating to rating of downTrack
5:    set newRating to oldRating - 20
6:    set rating of downTrack to newRating
7:  end tell

It first makes a variable to hold the track I want to downgrade and skips to the next track in the currently-playing playlist. Then it goes to work downrating the subpar track by one star (which is equivalent to 20 points in AppleScript terms).

Why does it skip to the next track before downrating? Recall that my smart playlist contains only tracks with 3 or more stars. If I downrate a playing track to 2 stars, it’s immediately removed from the playlist, there’s no selected track, and iTunes stops playing. Skipping to the next song before downrating ensures that the music continues.

And no, of course I didn’t think of that before I wrote the script. I endured several music interruptions before I realized what was going on and how to prevent it.