Search code examples
macosapplescriptitunesrating

Selecting all tracks in iTunes with AppleScript


I have this very basic AppleScript which I'm trying to run on my Mac to remove the ratings from all my songs in iTunes:

tell application "iTunes"
    set sel to every track in library playlist
    repeat with i from 1 to the count of sel
        set rating of track i in sel to 0
    end repeat
end tell

I've never written anything in AppleScript before, but thought I'd give it a shot (since it's supposed to be so intuitive). Unfortunately, I receive this error when I try to run the script:

error "Can’t get every track of library playlist." number -1728 
from every «class cTrk» of «class cLiP»

What is this error? Is there an alternate way of selecting the tracks in iTunes? Thanks for any help.


Solution

  • I don't entirely know why, but the answer is that the library playlist doesn't actually contain tracks. Strange, I know, but since you just want to run this over every track, there's an even simpler solution. Rather than every track of library, just use every track; this will get literally every track in the application, which is what you're trying to do. And with a few other simplifications, this becomes

    tell application "iTunes" to set the rating of every track to 0
    

    The tell application "iTunes" to ... syntax is just like an ordinary tell block, but it's only one statement long and doesn't take an end tell. And you can automatically run the set command over every entry in the list at once, so that's all you need. In general, you rarely need to enumerate via indices; for instance, for something closer to your solution, there's the equivalent

    tell application "iTunes"
      repeat with t in every track
        set the rating of t to 0
      end repeat
    end tell
    

    This avoids the indexing, and will also likely be faster (though the one-liner will probably be fastest, if there's a difference).