I just wrote my first ever AppleScript to solve a problem I’ve had for some time. As I’ve mentioned several times before, I use the MPD music player on my HTPC to play music through my amplifier while controlling playback using my laptop or mobile phone. This works like a charm and I’ve been really satisfied with this setup — until I fell in love with iTunes’ Genius function.
I use iTunes on my MacBook and mainly at work, either listening through my headphones or streaming music to the office speakers using our AirPort Extreme. As my library is rather diverse, I like to use Genius to get an ad hoc playlist of similar songs to avoid the “shuffle all, press next until a good song comes along” selection method. Needless to say, Genius has worked fabulously. However, when I come home and start playing music through MPD, I’m back to the shuffle all hell since I can’t be bothered creating playlists manually.
So this got me thinking: Is there any way I can use iTunes Genius together with MPD? The answer is yes, and the tool I used is AppleScript.
It’s not a complicated script, but it took me some hours to get it together since I’ve never written any AppleScripts before. The idea is to get the current playlist from iTunes (e.g. the currently playing Genius playlist) and look up and add each song to MPD. This of course requires that MPD has access to the same songs as iTunes by some means. In my case, I use a simple bash script to rsync my iTunes library on my MacBook to the HTPC’s MPD library:
rsync -tr --del --progress --perms --chmod=Da+rx,Fa+r /Users/bostrom/Music/iTunes/iTunes Music firstname.lastname@example.org:/media/lacie2/music
I run this script manually every time there’s been any changes to my iTunes library. This way MPD always has the exact same library as iTunes, and thus there should be no problem to replicate any iTunes playlist to MPD.
The script itself, at the time of writing, looks like this:
set mpdHost to "localhost" set mpdPort to "6600" set mpcCommand to "mpc -h " & mpdHost & " -p " & mpdPort & " " tell application "iTunes" set allTracks to every file track in current playlist do shell script mpcCommand & "clear" repeat with i from 1 to (length of allTracks) -- grab song set song to item i of allTracks -- construct search song command for mpc set searchCommand to mpcCommand & "search artist "" & (artist of song) & "" title "" & (name of song) & """ if album of song is not "" then set searchCommand to searchCommand & " album "" & (album of song) & """ end if -- execute command and grab the filename set filename to do shell script searchCommand -- add song if we got a filename if filename is not "" then do shell script mpcCommand & "add "" & filename & """ end if end repeat end tell
The script can be run from anywhere, but a convenient location is the iTunes script folder in ~/Library/Scripts/Applications/iTunes. This way, the script shows up in the scripts menu when iTunes is focused.