AppleScript iTunes example: How to search for a song

AppleScript iTunes search FAQ: How do I search for an iTunes song using AppleScript?

AppleScript iTunes song search and play example

I'm not sure if the following AppleScript example is the best way to search for an iTunes song and then play that song using AppleScript, but it is one way that I discovered recently while working on my AppleScript alarm clock application.

This example AppleScript code launches iTunes, searches for any songs in the playlist named "Library" whose name contains the string "Young at Heart" and whose artist name contains the string "Bennett", and then plays all the tracks it finds:

tell application "iTunes"
    set results to (every file track of playlist "Library" whose name contains "Young at Heart" and artist contains "Bennett")
    repeat with t in results
        play t
    end repeat
end tell

AppleScript iTunes song example - discussion

The action in this AppleScript iTunes search example happens in the line with the strings "every file track of playlist" and "whose name contains" and "artist contains". AppleScript can be verbose, but a nice thing about it is that this line (or at least everything within the parentheses) is self-explanatory, so I won't go into detail here. Suffice it to say that if you want to search for other track names, or songs by other artists, just change the strings that I'm showing in the code above.

On the rest of that same line of code I create an AppleScript list named tracks, and set it equal to the results of that search. Then on the following line of code I use the AppleScript "repeat with" syntax to play all of the iTunes tracks that are found in the search.

Of course if you just want to play an iTunes track and you know the name of that track you don't need to go through all this trouble. You can just play the track with AppleScript code like this:

tell application "iTunes"
    play track "Peanuts Theme Song" of playlist "Library"
end tell