Learn about Windows PowerShell
[Disclaimer: this is a reprint of a previously published article from the TechNet Script Center FunZone. The FunZone was not migrated from our old platform. It is printed here due to popular demand.]
This is part three of a three part series of articles about using VBScript to script iTunes. The first article was published last Sunday, and the second article was published yesterday.
The Playlist’s the Thing
By default all your songs are included in the iTunes library and can be accessed through the LibraryPlaylist object. However, songs can also be included in one or more custom playlists. Have a hankering for Beatles songs and nothing but Beatles songs? Then create a custom playlist consisting of only Beatles songs. Dying to hear some reggae? Then create a custom playlist consisting of only reggae songs. Got a bad case of disco fever? Then create a custom playlist of – well, forget that one. There are some things even the Scripting Guys can’t recommend; you’re on your own when it comes to disco.
The important thing – at least for our purposes – is that you can use scripts to create, delete, and manage custom playlists. Let’s start with a simplest task – retrieving information about all your playlists – and then go on from there.
Retrieving All Your Playlists
Let’s start out by retrieving a list of all our iTunes playlists. In other words, let’s start out with a script that looks like this:
Set objApp = CreateObject("iTunes.Application")
Set colSources = objApp.Sources
For Each objSource in colSources
Set colPlaylists = objSource.Playlists
For Each objPlaylist in colPlaylists
Wscript.Echo " " & objPlaylist.Name
Yes, it’s a little crazy, but that’s because the iTunes object model can be a bit convoluted at times: in this case we need to create a Sources object, get a list of the playlists found in the Sources object, then get a list of the playlists found in each of those playlists. Confusing? Maybe it will help to take a look at the output:
My Top Rated
Top 25 Most Played
As you can see, we have two primary sources – Library and Radio – and each of these sources contains at least one playlist. A bit confusing at first glance, but there’s a method to the madness.
As for the script itself, we start out by creating an instance of the iTunes.Application object; we then use this line of code to retrieve a list of all our iTunes sources (which, on our test computer, is a collection with just two items: Library and Radio):
Once we have the collection we set up a For Each loop to walk through all the items. Inside that loop we echo back the source name, then use this line of code to retrieve a collection of all the playlists included in that source:
From there we set up a second For Each loop to echo back the name of each of those playlists:
After we’ve done that we loop around and repeat the process with the next item in the Sources collection.
We know. But remember, you can always use the code as-is without having to worry too much about how it all works. (Although if you play around with this a little bit you’ll catch on in no time.)
Incidentally, playlists contain more properties than simply the playlist name. For example, here’s a script that echoes back property values for the Library playlist:
Set objPlaylist = objApp.LibraryPlaylist
Wscript.Echo "Kind: " & objPlaylist.Kind
Wscript.Echo "Duration (seconds): " & objPlaylist.Duration
Wscript.Echo "Shuffle enabled: " & objPlaylist.Shuffle
Wscript.Echo "Size (bytes): " & objPlaylist.Size
Wscript.Echo "Repeat mode: " & objPlaylist.SongRepeat
Wscript.Echo "Playing time: " & objPlaylist.Time
Wscript.Echo "Visible: " & objPlaylist.Visible
Needless to say, you can get that same information for a single playlist … well, assuming you know how to connect to a single playlist. Which brings us to the next section of this article.
Binding to an Individual Playlist
Any time you have a big, comprehensive object model there will always be multiple ways to achieve the same goal. What we’re going to do here is to show you one reasonably easy way to connect to an individual playlist. Are there other ways to connect to an individual playlist? Sure. But we’ll let you figure those out yourself.
Here’s a simple way to connect to the playlist named My Playlist (and, while you’re at it, to echo back the properties of that playlist):
Set objSource = colSources.ItemByName("Library")
Set objPlaylist = colPlaylists.ItemByName("My Playlist")
Select Case objPlaylist.Kind
Case 0 strKind = "Unknown playlist kind."
Case 1 strKind = "Library playlist."
Case 2 strKind = "User playlist."
Case 3 strKind = "CD playlist."
Case 4 strKind = "Device playlist."
Case 5 strKind = "Radio tuner playlist."
Wscript.Echo "Kind: " & strKind
Yes, we did get a little fancy there, didn’t we? We even included a Select Case statement that tells you which kind of playlist you’re dealing with (as opposed to simply echoing back an integer value). For now, though, the only portion of the script we need to concern ourselves with comes in the first few lines:
What we’re doing here is creating an instance of the iTunes.Application object and then retrieving a collection of iTunes sources. From there we call the ItemByName method to connect us to the Library, bypassing any other sources (like Radio):
Note. Why did we go straight to the Library? Well, that’s where most of your playlists will be found. Therefore, why not go straight to the Source?
So to speak.
After connecting to the Library we use this line of code to return a collection of all the Library playlists:
And then we once again use the ItemByName method to bind us to the My Playlist playlist:
See? That wasn’t so bad, was it?
Creating Your Own Playlist
What’s that? You say you’re looking at your copy of the iTunes application, and you don’t have a playlist named My Playlist? We’re not surprised; that’s a playlist we created ourselves. And we did it using this ridiculously-simple script:
Set objPlaylist = objApp.CreatePlaylist("My Playlist")
No, we’re absolutely serious: all it takes are two lines of code to create a new playlist. Create an instance of the iTunes.Application object, then call the CreatePlaylist method, passing along the name of your new playlist (in this case, My Playlist). The net result? Here’s the net result:
Adding Songs to a Playlist
That’s a good point: a playlist without any songs is like a day without sunshine (a phenomenon those of us who live in the Seattle area are all-too-familiar with). Let’s see what we can do about taking a song from our library and adding it to our new playlist:
Set objLibrary = objApp.LibraryPlaylist
Set colTracks = objLibrary.Tracks
Set objSong = colTracks.ItemByName("Easy Love")
In order to add a song to a playlist we need to do two things: we need to make a connection to the playlist (My Playlist) and we need to make a separate connection to the song itself. To do that we start out in familiar fashion, working our way down the object model and then using the ItemByName method to retrieve the My Playlist playlist:
After we do that we connect to the iTunes library, retrieve a collection of all the songs. Then, again, we use the ItemByName method to bind to a particular song (in this case, Easy Love):
That gives us the two things we need: an object reference to the playlist (objPlaylist) and an object reference to the song (objSong). All we have to do now is call the AddTrack method to add the song to the playlist:
It’s that easy.
Of course, if all you want to do is add a single song to a single playlist you’ll probably find it faster and easier to do that by hand than to write a script. Scripts don’t really come in handy until you begin dealing with multiple songs.
For example, here’s a script that takes advantage of the iTunes search capability to add all the Rock songs to My Playlist.:
Const ITPlaylistSearchFieldAll = 0
Set colTracks = objLibrary.Search("Rock", ITPlaylistSearchFieldAll)
For Each objSong in colTracks
Set objSong = colTracks.ItemByName(objSong.Name)
Pretty easy. We simply search the Library for all the Rock songs; as we saw earlier, the Search method will retrieve a collection of such songs for us. We then simply set up a For Each loop to walk through that collection, binding to each song in turn and then using the AddTrack method to add that song to the playlist.
By the way, this is how you would create a playlist consisting entirely of Beatles songs. Search for all the songs where the artist name is Beatles, then add those songs to the playlist. Just that easy, just that quick.
Here’s an interesting bit of code. After binding to the iTunes library this script retrieves a collection of songs (tracks), then uses the Count property to determine the total number of songs in the collection. From there, the script goes into a For Next loop where it uses the VBScript function Rnd to randomly generate a value between 1 and the total number of songs in the collection. The script then uses the Item method to connect to the song with the generated index number, then adds that song to the playlist. After randomly selecting three songs and adding them to the playlist, the script exits the loop and ends. Cool, huh?
Here’s the code:
intHighNumber = colTracks.Count
intLowNumber = 1
For i = 1 to 3
intNumber = Int((intHighNumber - intLowNumber + 1) * Rnd + intLowNumber)
Set objSong = colTracks.Item(intNumber)
Playing the Songs on a Playlist
True: it would be kind of silly to use a script to generate a playlist yet not be able to play the songs in that playlist. Okey-doke: here’s a script that connects to the My Playlist playlist and then uses the PlayFirstTrack method to start playing the first song in the list:
By default iTunes will then continue playing all the songs in the playlist.
Deleting a Playlist
Nothing lasts forever, including iTunes playlists. If you ever want to get rid of a playlist just run a script similar to this:
Needless to say there isn’t much to explain here: bind to the playlist, call the Delete method, and then get on with your life.
Bonus Script: The Name That iTune Game
If you’re looking for something different to do with your iTunes software, how about a “Name That iTune” game? Although this is far from a finished product, the following script demonstrates how you could create a game that:
Randomly chooses a song from your iTunes library.
Plays the first 10 seconds of the song.
Asks you to name the song.
Reports back the answer.
Admittedly, in its current format the game isn’t quite ready to replace World of Warcraft or The Sims. But it does give you a foundation to work from:
Set colTracks = objPlaylist.Tracks
intTracks = colTracks.Count
intHighNumber = intTracks
Wscript.Echo "What's the name of this song?"
Wscript.Echo "Answer: " & objSong.Name
Hey, What About My iPod?
Your what-pod? Oh, right, your iPod; we almost forgot. As it turns out, the iPod itself is just another iTunes source; as long as your iPod is plugged into the computer you can write scripts that can interact with the device the same way they interact with other sources and playlists.
Having said that, we should caution that the only device the Scripting Guys had for testing these scripts was an iPod Shuffle, and the Shuffle has limited capabilities compared to other models. Therefore, all we’re going to show you today is how you can connect to an iPod and retrieve the collection of songs currently on the device. Can you do anything more than that with a script? Maybe, but that will likely depend, at least in part, on the type of iPod you have. Use this script as a starter, and then go from there.
Use what script as a starter? This script:
Set objSource = colSources.ItemByName("IPOD")
Set objPlaylist = colPlaylists.ItemByName("IPOD")
For Each objTrack in colTracks
Wscript.Echo "Name: " & objTrack.Name
We’ve done things a little different this time around. As you can see, we start out by creating an instance of the iTunes.Application object, then create an object reference to the Sources object. This time around, however, we don’t cycle through all the sources looking for one representing the iPod (although we could have). Instead, we use the ItemByName method to connect to the source with the name IPOD. That binds us directly to the IPOD.
Note. Do all iPods have a Source name of IPOD? To tell you the truth, we don’t know. But there’s an easy way to find out: just plug your iPod into the computer and see what name shows up in iTunes.
From there we create an object reference (colPlaylists) representing all the playlists on the iPod, then use the ItemByName method to bind to the IPOD playlist. (Again, we can’t do that because the shuffle has only a single playlist on it.) We then retrieve the collection of tracks and echo back the name of each song:
You’re right: that’s pretty much the same approach we used when retrieving the names of all the songs in the Library. And that’s the point: as far as the script is concerned the iPod is, like the Library, just another Source.
Incidentally, if you have a Shuffle then you know that one way to copy songs onto the Shuffle is to configure iTunes so that it synchronizes the Shuffle with a specified playlist. Here’s an instance where scripting can come in handy: you can use scripts to periodically change/update the songs in that playlist. The next time you synchronize iTunes and the Shuffle, you’ll get a new set of songs on your iPod.
That is all there is to using VBScript to work with your iTunes collection. Join me tomorrow as I begin a new week on the TechNet Script Center. I invite you to follow me on Twitter or Facebook. If you have any questions, send e-mail to me at firstname.lastname@example.org or post them on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy