Wednesday, December 21, 2011

Dumbing down iTunes smart playlists

I wanted to make "dumb" copies of a few Smart Playlists in iTunes and have the copies updated periodically. Why I want that is part of a scheme not fully baked, so I won't go into it, but I thought this part was worth documenting.

I've had some experience in the past with AppleScript, and it seemed like it would tear this up. It took some time and research, but I eventually came up with this.

tell application "iTunes"
tell source "Library"
repeat with srcPlaylist in {"5 Best", "Played most", "Abbreviated list", "Good sample"}
set cpyPlaylist to "A copy of '" & srcPlaylist & "'"
delete (every track) of playlist cpyPlaylist
duplicate (every track) of playlist srcPlaylist to playlist cpyPlaylist
end repeat
end tell
end tell

That copies a playlist named "Played most" to another playlist named "A copy of 'Played most'". The copy playlist has to exist already (the script won't create it), and whatever is in it will be deleted every time the script is run. You can run it from the command line by putting it in a file and using "osascript" to execute it.

One hangup I had is that having a quotation mark in an AppleScript string is not supported in a way that I'd like as a programmer of more user-hostile languages. I also tried to use Automator for this, and that went nowhere.

A more advanced script might check whether iTunes is running before blithely tossing commands at it. It might also create playlists that aren't there or take some kind of safety precautions. I doubt that I'll expand my AppleScript knowledge for the sake of those "advanced" features, but I'd be happy to hear from someone else who's done it.