Search code examples
applescriptitunes

Applescript - How to iterate over tracks


I'm a newbie in applescript. I was trying to learn it from various sources, such as Doug's site, macscripter and this forum

Just for learning purposes, I was trying to print on the screen all the tracks names using this code:

tell application "iTunes"
    set myTracks to (tracks of library playlist 1)
    repeat with aTrack in myTracks
        get name of aTrack
    end repeat
end tell

But it only prints one track name, probably the last one...

So, how is the best way to iterate over a list?

TIA,

Bob


Solution

  • Your code is fine; the reason nothing seems to happen is that all get ... does is look up a value and return it. However, you don't do anything with the returned value, so it is ignored, and only the last iteration of the loop returns anything. You need to do something (anything) inside the loop which is visible to the outside world: assign to a variable, display a dialog, whatever.

    If you want to collect a list of the names of items, you can do the following:

    tell application "iTunes"
      set trackNames to {}
      repeat with aTrack in tracks of library playlist 1
        set trackNames to trackNames & name of aTrack
      end repeat
    end tell
    

    However, you can tighten this up. One powerful feature of AppleScript is that just as you can get the name of a track, you can get the name of every track in a list and iterate over that:

    tell application "iTunes"
      set trackNames to {}
      repeat with aName in name of tracks of library playlist 1
        set trackNames to trackNames & aName
      end repeat
    end tell
    

    But at this point, you don't even need the loop, and you can use the much simpler

    tell application "iTunes" to name of tracks of library playlist 1
    

    And as a bonus, it'll be much faster: in a quick test I did, the three versions took 16.189 seconds, 32.656 seconds, and 0.296 seconds, respectively.