Friday, March 18, 2005

iTunes Playtlist with cElementTree

python :: programming :: music



When we moved to Colorado from Maryland in January, a Tibetan friend of
ours who is a monk helped us pack, drive, unpack, and setup house when
we got here. During the drive, we spent many hours practicing English,
Tibetan, and listening to "injee" music on my iPod. There were certain
songs that he could listen to more easily than others. It was sometimes
surprising to me the songs where lyrics were enunciated well enough to
be mimicked without understanding the content. The one that made me
laugh the hardest was "Cold As Ice" by Foreigner... there is something
totally hilarious about driving cross-country with a Tibetan monk, both
of you singing "She's as cold as ice!" at the top of your lungs. It's
one of those moments you know will stick with you forever. Another good
one was KC & the Sunshine Band's "Shake Your Booty" -- it turns out
English "shake" is cognate with a Tibetan colloquial word of similar
pronunciation and meaning.


Anyway, I was supposed to build CDs of photos and music from our
several weeks together and send them back home to Lama Gyaltsen. iTunes
exports playlists in several formats, including XML. This was a perfect
excuse to play with ElementTree some more, while the CDs burned (that's
another cool thing about iTunes: got a play list that's 3 and a half
hours worth of music and you want to burn to CD? No problem! It splits
them up for you. Save your brain cells for the important stuff like
playing with python).

Here's the code:

import cElementTree as et
filename = '/Users/oubiwann/Desktop/Mix - Lama Gyaltsen.xml'
tree = et.parser(filename)
root = tree.getroot()
template = '%s: %s'
for i in root.find('./*/dict').getchildren():
if i.tag == 'dict':
data = i.getchildren()
for j in range(0,len(data)):
if data[j].tag == 'key':
if data[j].text == 'Name':
print template % ('Song Name', data[j+1].text)
if data[j].text == 'Artist':
print template % ('Band Name', data[j+1].text)
if data[j].text == 'Total Time':
converted = '%s:%.2s' %
divmod(int(data[j+1].text), 60000)
print template % ('Length', converted)


Update: Fredrik Lundh has just blogged about this :-) He has a
added simpler loader for for iTunes playlists to ElementTree. Read
about it here.


No comments: