How to shuffle an iTunes 11 playlist (using AppleScript)

10 January 2014 by Lincoln Ramsay

iTunes 11 removed a feature I used quite a bit, the ability to shuffle a playlist.

No, I don’t mean playing the songs in a random order, I mean changing the unsorted order of the songs in the playlist.

Today, this annoyance finally got the better of me so I searched for a solution.

Sadly, my searches didn’t actually turn up anything useful. I mean… it’s been over a year and nobody has figured out how to sort a playlist?

I know just enough AppleScript to be dangerous, so I figured I’d have a go. Because this really shouldn’t be a hard thing to do. Turns out I was mostly right.

Getting the tracks from the current playlist is easy.

set thePlaylist to (get view of front browser window)
set theTracks to tracks of thePlaylist

Doing a Knuth shuffle on the list is easy.

set trackCount to count of theTracks
repeat with i from trackCount to 1 by -1
    set j to (((random number) * (i - 1)) as integer) + 1
    set tempTrack to theTracks's item i
    set theTracks's item i to theTracks's item j
    set theTracks's item j to tempTrack
end repeat

Here I hit a snag. You see, I want to replace the playlist’s contents with this sorted list but when I remove the songs from the playlist, my list ends up with a bunch of dangling references. Not to worry, you can resolve a reference to get the canonical handle, that remains valid even when the playlist is cleared.

set thePersistentTracks to {}
repeat with theTrack in theTracks
    set theId to persistent ID of theTrack
    set myTrack to the first item of (every track whose persistent ID is equal to theId)
    copy myTrack to the end of thePersistentTracks
end repeat
set theTracks to thePersistentTracks

Then you just clear the current playlist and set its tracks to the list you have.

delete tracks of thePlaylist
repeat with theTrack in theTracks
    duplicate theTrack to thePlaylist
end repeat

Of course, that’s not particularly efficient and it’s made worse by iTunes re-indexing for every item. You can suppress that with this.

set oldfi to fixed indexing
set fixed indexing to true
-- change playlists here
set fixed indexing to oldfi

Put it all together and you get this script. Unzip and move the script to ~/Library/iTunes/Scripts (create that directory if it’s not already there). Then you’ll have a Shuffle menu item under the script menu that shuffles your current playlist.

Shuffle menu item