itunes -- add track to playlist?

this sounds like it should be easy but for some reason it’s eluding me. Here’s a sample of what I’ve been playing around with:

tell application “itunes”
…set _library to (library playlist 1)
…set _song to (tracks of _library whose name is “song”)
…add _song to user playlist “playlist”
end tell

FYI I’ve been trying to adapt this from another script I have, which already works fine, creating a new playlist and adding a track to it:

…copy (get a reference to (make new user playlist with properties {name:“playlist”})) to _playlist
…duplicate _song to _playlist

I just want to add a track to a playlist that already exists, without creating a new one. Shouldn’t that be easier rather than harder??

The ‘add’ command in this case is meant to be used for importing files from Finder into iTunes. When you’re dealing with references within iTunes itself, you should use the ‘duplicate’ command.

tell application "iTunes"
	set _library to (library playlist 1)
	set _song to (tracks of _library whose name is "song")
	duplicate _song's first item to user playlist "playlist"
end tell

Note that this only copies the first match. Some modification is necessary to make the script accept multiple matches.

Duplicate didn’t work either. But, I figured it out. Or, I didn’t figure it out, because I don’t quite know why one worked and another didn’t, but I got it to work by simplyfying:

tell application “iTunes”
set _library to (library playlist 1)
duplicate (tracks of _library whose name is “song”) to user playlist “playlist”
end tell

Yeah, it only works for one track, but it’s supposed to act like a jukebox, adding one track at a time.

The payoff will be jukebox functionality added to the next version of my little Xcode app, nTunes (search for it on scriptbuilders to see what it’s all about).


iTunes and Finder are different apps. When you duplicate tracks, you’re doing it within iTunes, while adding tracks utilizes a Finder reference. You can get a reference to the track (file) in the Finder with the ‘location’ property. Here’s an example of doing the same thing with the iTunes ‘add’ command:

tell application “iTunes”
set new_pl to (make new playlist with properties {name:“My Playlist”})
set lib_pl to first library playlist
set target_track to first track of lib_pl whose name is “The Day Begins”
– get a reference to the file in Finder
set track_loc to location of target_track
– add file to playlist
add track_loc to new_pl
end tell

‘location’ returns a reference to the song file which is used in the ‘add’ command.