Get iTunes artwork in Python

While thinking of uses for my tiny 128×128 TFT, I thought it would be cute if it showed the currently playing iTunes artwork. Little did I know the rabbit hole it would lead me down. Surely I thought somebody else had wanted to get the currently playing iTunes artwork from within python, I mean, it seems pretty tame compared to other atrocicities I’ve witnessed. But alas, my (albeit fairly short-lived) google searching revealed nothing, save some outdated StackOverflow questions. One thing it did turn up however, was ScriptingBridge, Apple’s python module to allow a python script interact with other OS X applications. I found a snippet of code to get the object for the currently playing song in iTunes, and took over from there. After much poking and probing (thank goodness for dir()), I found what I needed, a TIFF representation of the artwork for the currently playing song in iTunes. Using the magic of PIL (or Pillow in my case) it was trivial to convert this into a workable format for my needs. There is still one road-block, and that would be that it seems to cause a memory leak. After running the TFT script for a little over 30 minutes, the script had managed to consume 42 gigabytes of memory (that’s RAM, not disk space folks), before locking up my entire computer. I was alerted to the issue by OS X kindly telling me that I had run out of disk space on my startup disk, the paging file was massive. Anyways, I’m sure somebody more well versed in the intracies of ScriptingBridge would be able to locate the issue and take care of it. Please leave a comment if you know what’s wrong 🙂

from PIL import Image
from cStringIO import StringIO
from ScriptingBridge import *

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")

img = Image.open(StringIO(iTunes.currentTrack().artworks().firstObject().rawData()))

Leave a Reply