How do I tell iTunes to search my Library for something?
AppleScript is not for scripting the UI of applications. The search command is going to return to your script, in a variable, a list of tracks that match your search. You have to do something with them, like add them to a playlist so you can tell iTunes to play them. So something like this ought to work: tell application “iTunes” if not (exists playlist “Script Playlist”) then make new playlist with properties {name:”Script Playlist”} else delete every track of playlist “Script Playlist” repeat while (number of tracks of playlist “Script Playlist”) > 0 delay 0.1 — wait for the library to clear out end repeat end if set trax to (search library playlist 1 for “Peter Gabriel”) set p to false repeat with t in trax try duplicate t to playlist “Script Playlist” if not p then repeat while (number of tracks of playlist “Script Playlist”) = 0 delay 0.
The best iTunes scripting resource I know of is Doug’s AppleScripts for iTunes. It sounds like this one does most of what you want.
You would, possibly, want to use a variable for the name of the playlist… There is a bit of logic in the script to start playing after the first track has been added, so you don’t have to wait for the music to start until all the tracks have been added. Also, take note of the repeat loops that wait for iTunes to do various things. iTunes is asynchronous — if you tell iTunes to do something, it’ll let your script continue while it does it. So at a couple points I had to put in a loop to make sure iTunes is finished with what the script told it to do. It’s actually not a factor on my Mac (dual G5) but it could be on yours.
My command of Applescript is pretty weak, but even I’ve encountered the ways in which it is hard to script iTunes to do what you want. That said, there’s a good discussion board on the topic of scripting itunes over at ipod lounge.