Streaming Last.fm in Ruby
Irecently have been unlucky enough to experience a hard drive crash. The unrecoverable type of crash. Being on the light side for backups, I’ve lost all my (legally obtained of course) collection of mp3. Tons and gigs of them. I’m not crying because I’m a man but I can tell you that my heart bleeds. So as a result, I pretty much rely on internet radios now, among which last.fm. The trick though, is that I run Linux so their default player (iTunes nastiness) doesn’t work for me. And I hate iTunes anyway. Amarok is much better but I own an Airport Express and I can’t easily stream to my Airport using Amarok. Long story to say that I needed some more creativity.
Turns out that the last.fm protocol is pretty simple. A very nice person has retro-engineered it in a pretty thorough manner. So I won’t repeat everything that has already been explained in detail, just sum up and add a couple more missing things:
- The last.fm stream is a plain old MP3 stream (more poms for the Maven fans out there). It doesn’t have any Shoutcast style meta data.
- On the other hand, they insert a “SYNC” string in there signal anytime the song changes in there stream, to let you know what’s happening.
- To get what’s currently playing they have a web service (the kind of RESTful type) that can be invoked anytime and returns all kind of information about the song. That with the previous point allow you to know what’s happening. There are also a few more services to skip, love, ban and let them know how you really feel right now.
- To start the interaction, you only need to login by invoking a URL, sending you username and password. I can hear your knees jerking my security-aware friends, but don’t worry, the password is MD5 encoded. They reply to you with a session id that you pass in any subsequent calls.
I told you it was simple. So I went ahead and implemented the whole thing in Ruby, which turned out to be equally simple, once all the aforementioned details were clear. And here is the thing:
Now what do you do with that little “out” variable? Pretty much everything you want. You really can’t pass a file, to stream everything to your disk and therefore get MP3s for everything you’re listening. That would be illegal. Plus the RIAA people don’t like it and we should really listen to them, they act for the good of music.