Journal

Show latest Last.fm plays on your Symphony site

Symphony has a hunger for XML. Thankfully Last.fm's API shares this appetite.

At the top of my blog I have added the name of the last track scrobbled to Last.fm. Symphony made this so easy, eating a biscuit with a fresh brew after five minutes. Here's how:

First you need a Last.fm user account, and one of the various applications to scrobble your tracks from iTunes (or Windows Media Player, if your life is broken). Then you need to grab an API key. The key will be a hash that looks something like this (note: this is not my real API key!).

3d21e002930b853d2f048e517c577ec7

You can then create a URL using the Last.fm API to return your recent tracks as XML. We will use the user.getRecentTracks method of the API. Your URL should be in this format:

http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user={your-username}&api_key={your-api-key}

Log in to your Symphony site and create a new Data Source, choosing "Dynamic XML" as its source. Paste your API call URL into the URL field and update the cache value to something small, between 1 and 10 minutes should do.

Figure 1. Last FM Data Source
Figure 1. Last FM Data Source

Note that I have also added the XPath expression //track[1] so that only the first track node is included in my Page to keep things lean.

Attach this Data Source to your Page and fire up ?debug to check you can see the fresh track node. You can? Great! I'm glad you've been keeping up.

Figure 2. Last FM Data Source debug XML
Figure 2. Last FM Data Source debug XML

All you need now is a little XSLT magic to write this content into your page. Where you want the track name to appear, add a template match to the track node above:

<xsl:apply-templates select="/data/last-fm/track" mode="last-fm"/>

And neatly out of the way you can create a template to handle the rendering of the content. My template looks like this. Notice I'm checking whether the track has a nowplaying attribute and changing the label accordingly.

<xsl:template match="track" mode="last-fm">

    <xsl:choose>
        <xsl:when test="@nowplaying='true'">
            <xsl:text>Currently listening to </xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>Recently listened to </xsl:text>
        </xsl:otherwise>
    </xsl:choose>

    <xsl:value-of select="concat(name, ' by ', artist)"/>

</xsl:template>

How stupendously easy!

The kettle's boiled. Time for a cuppa.

Comments

Frederick Yocum

Hmmm… thanks Nick for providing a tasty morsel of Symphony goodness to have with tea.

Share your thoughts