filerandomapplescriptitunesplaylists

Get a random file from a folder and add it to an iTunes playlist


I have looked at some answers which tell me how to get random files from folders, and some which can deal with iTunes playlists. Haven't been able to put these together.

What I'm looking for is a way (I was thinking in AppleScript) of getting the 200 songs in my Folk playlist folder on my hard drive, randomly selecting 20 of those songs, and then adding them to an iTunes playlist.

I am aware smart playlists can kind of do this, but I want to do it as much outside of iTunes as possible, because a lot of my music is in folders and not on iTunes per se.

I'd be really grateful of any help with:

  1. Getting 20 random files from a folder And
  2. Then pushing them into a playlist.

I did wonder if there was some way I could get the number of files in per cent (20% of the files in Folk), but it's not really a deal breaker!

Thanks in advance to anyone who can help me!

Tardy


Solution

  • Here is the script you're looking for. I leave the first answer because it could also be useful for others.

    property RList : "my random list" -- name of the random list
    property ListGenres : {"Rock", "Pop", "Soundtrack", "Jazz"} -- your list of genres
    property NumPerGenre : {3, 2, 5, 4} -- the number of songs per genre
    
    tell application "iTunes"
    if exists user playlist RList then -- check if the playlsit exists or not
        delete tracks of user playlist RList -- delete all current tracks of the play list
        repeat while (number of tracks of playlist RList) > 0
            delay 0.1 -- wait for the library to clear out, because iTunes is asynchronous !
        end repeat
    else -- creation of the play list
        set MyPlayList to make new user playlist with properties {name:RList}
    end if
    
    repeat with I from 1 to (count of ListGenres) -- loop per genre
        set ListTracks to (tracks whose genre is (item I of ListGenres))
        repeat with J from 1 to (item I of NumPerGenre) -- loop to add x tracks per genre
            set TheTrack to item (random number from 1 to (count of ListTracks)) of ListTracks
            duplicate TheTrack to playlist RList
        end repeat -- loop for all tracks per genre
    end repeat -- loop by Genre
    play playlist RList -- start to play !  
    end tell
    

    I've put many comments to make it clear (I hope). In this example, I have 4 genres, and I will get 3 songs of the first genre, 2 songs of the second genre, ...and so on. you can change these properties, as long as the list of genre count same number of items as list of numpergenre.

    Unfortunately, since iTunes 11, the shuffle attribute can't be set via script, you must set it manually in iTunes to play the list randomly (it can be set once for all)