Welcome, guest | Sign In | My Account | Store | Cart

Here are two examples showing how to script iTunes for Windows with Python. See below under "Discussion" for additional comments and explainations.

Python, 81 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import win32com.client

def removeDeletedTracks():
  """This function will remove every song that is not currently accessible from your iTunes library"""
  #First, we create an instance of the iTunes Application
  itunes= win32com.client.Dispatch("iTunes.Application")
  
  #The ITTrackKindFile value will be use to check if a track is a physical file
  ITTrackKindFile=1
  
  #The tracks list object is obtained from the iTunes instance  with the following expression:
  #itunes.LibraryPlaylist.Tracks
  #this tracks list object has two fields/methods of interest:
  # The Count field contain the total number of tracks in your library
  # The Item(numTrack) method will return the track with number numTrack
  #     (Be aware that the numbering of the tracks start at 1, NOT at 0)
  mainLibrary = itunes.LibraryPlaylist
  tracks = mainLibrary.Tracks
  numTracks = tracks.Count
  deletedTracks=0
  
  #(optional)We can create a log file in which the names of the deleted songs are written
  #log=open("deletedTracks.txt","w")
  
  while numTracks  !=0:
    currTrack=tracks.Item(numTracks)
    if currTrack.Kind == ITTrackKindFile:
      if currTrack.Location == "":
        #Uncomment the lines below if you want to have the name of the deleted files saved in the log file
        #name_artist=currTrack.Artist
        #name_song=currTrack.Name
        #log.write("[%s] [%s]\n"%(name_artist.encode("utf-8"),name_song.encode("utf-8")))
        currTrack.Delete()
        deletedTracks+=1
    numTracks-=1
  
  
  if deletedTracks > 0:
    if deletedTracks == 1:
      print "Removed 1 dead track."
    else:
      print "Removed " + str(deletedTracks) + " dead tracks."
  else:
    print "No dead tracks were found."


    
def updateLyricsAndCreatePlaylist():
  """The aim of this function is to automatically add lyrics to the songs in your library.
  Additionally, a playlist named "SongsWithLyrics" is created, which will contain all the songs to 
  which lyrics have been added (so that you can find them easily if you feel like Karaokeing)
  Please note that it use a (non-provided) getLyrics function that, given an artist and a song name, 
  return the lyrics of the song or the None object if the lyrics are not available.
  """
  
  #We do the usual "initialisation" stuff, like in the removeDeadTracks function
  itunes= win32com.client.Dispatch("iTunes.Application")
  ITTrackKindFile=1
  mainLibrary = itunes.LibraryPlaylist
  tracks = mainLibrary.Tracks
  nbTracks = tracks.Count
  
  #We create a playlist named "SongsWithLyrics", which will contain all the updated songs
  playlist=itunes.CreatePlayList("SongsWithLyrics")
  
  for numTrack in range(1,nbTracks+1):
    currTrack = tracks.Item(numTrack)
    #Trying to access the lyrics field of WAV files seemed to raise an exception. Hence the following condition.
    if currTrack.Kind == ITTrackKindFile and currTrack.KindAsString!=u"WAV audio file":
      name_artist=currTrack.Artist
      name_song=currTrack.Name
      lyrics=currTrack.Lyrics
      #We update only songs which do not already have a lyrics
      if len(lyrics)==0:
        #The getLyrics function return the lyrics of a song (as a unicode string). I do not provide example sources for this function (see below)
        obtainedLyrics=getLyrics(name_artist,name_song)
        if obtainedLyrics!=None:
          #if we obtained the lyrics, we add the current track to our playlist...
          playlist.AddTrack(currTrack)
          #... and we update the lyrics field of the track
          currTrack.Lyrics=obtainedLyrics

Since most of the script for iTunes you can find of the web are written in AppleScript, I was wondering how I could script iTunes for Windows. Then I discovered that iTunes for Windows had a COM API. Python having a very nice interface to COM (thanks to the win32com module), that make it very easy to script iTunes with Python.

There is nothing very sophisticated here, but there may be some others "Python and iTunes users" that are not aware of this possibility (as I was just a month ago). So I thought I would write a small recipe (my first so far) for that. Additionaly, It makes for a simple introduction to COM programming with python.

You can download a documentation of the iTunes COM interface at the following address: http://developer.apple.com/sdk/itunescomsdk.html The doc is bundled with some C header, but don't worry, you do not need them. You only need the win32com module (which is already bundled with ActivePython)

I give two example scripts. The first one is used for removing the songs of your library whose files you have deleted outside python. (Very useful, if like me, you don't let iTunes manage your library). It is actually a simple port of a javascript example provided in the iTunes COM documentation.

The second one is a script I used to automatically add lyrics to the songs in my library. This script is of course not very useful in itself without the getLyrics function that provide the lyrics text. But it is a good example of how to create playlist and modify the fields of a song. I happened to have a small database of lyrics, so that was useful for me. If you are really interested in obtaining lyrics for your songs, look for lyrics website that provide a web API.

1 comment

eric casteleijn 13 years, 2 months ago  # | flag

Hey, this is pretty cool! Would you consider helping out on this project: http://code.google.com/p/autoqueue/ to port the crossplayer autoqueue[] plugin to iTunes for windows? Someone is already working on a iTunes for mac version, so maybe you could collaborate. I'd really like to have at least one windows based player supported, but since I'm not a windows user, I won't be able to do it/test it. I *will however help you port it and explain what needs to be done, and it shouldn't be too much work: It's basically just extending a base class and implementing a few player specific methods.

[*] Autoqueue is a crossplayer plugin that gets similar tracks to the ones you play from last.fm and puts them in the queue. It is smart enough not to play the same artists/songs for a configurable time, and has some other options. It works pretty well in creating a consistent yet not wholly predictable listening experience if you have a large and diverse library.

I suppose it's similar to the new genius feature, but more configurable, and from what I hear, for now the last.fm similarity searches are a lot better.

Created by Fabien C. on Fri, 3 Nov 2006 (PSF)
Python recipes (4591)
Fabien C.'s recipes (1)

Required Modules

Other Information and Tasks