ITunes/Applescript: get all tracks from (incomplete) album

albumapplescriptitunes

I try to write an Applescript that would sort playlists by album. That is, a playlist P might contain 20 tracks split on 4 albums (A1, A2…). Each album has 10 tracks, in other words, on this playlist, the albums on average only contain half of the tracks.

I have found a lot of examples where you can query iTunes for all tracks that belong to an album on the library level, typically something like this

set albumSongs to (every track of library playlist 1 whose album is currentAlbum)

while I want to do something like this

set albumSongs to (every track of playlist myPlaylist whose album is currentAlbum)

but compiling my example returns an error message Expected class name but found identifier. pointing at the track keyword in the line above.

Update:

The unfinished function I try to write where I want to get all tracks that belong to a certain album

on sortPlaylist(albumList, currentPlaylist)
    repeat with currentAlbum in albumList
        set albumSongs to (every track of currentPlaylist whose album is currentAlbum)
    end repeat
end sortPlaylist

It takes a list without duplicates of all albums (albumList) and the playlist (currentPlaylist) I want to work with. I still have no code to actually sort it (input is appreciated!) but the plan is to sort albumSongs in track order and then add the tracks to the playlist in order.

Best Answer

Try:

set playlistName to "playlist name"

tell application "iTunes"
    set playlistReference to first playlist whose name = playlistName
    set currentAlbum to album of current track
    set albumSongs to (every track of playlistReference whose album is currentAlbum)
end tell