Last listened to The Getaway by Immortal Technique (on 10 Mar 2010, 14:39)

I use last.fm and let it's audioscrobbler services keep a track of whatever music I listen to. As you can see, just below the navigation bar on this website I use its API to display the last track I listened to.

Here's what it looks like when it's in action:

It's incredibly easy to add this onto your website too, if you're an ASP.NET developer. Here's how.

Create a new User Control in your website, and call it MostRecentTrack.ascx. In the codebehind file, copy and paste the following:

protected XElement MostRecentTrack { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    GetLatestTrack();

    if (MostRecentTrack == null)
        LatestTrackHolder.Visible = false;
}


private void GetLatestTrack()
{
    MostRecentTrack = Cache["MostRecentTrack"] as XElement;
    if (MostRecentTrack != null) return;

    string xmlLocation =
        string.Format("http://ws.audioscrobbler.com/1.0/user/{0}/recenttracks.xml",
                      LastFmUsername.Text);

    try
    {
        MostRecentTrack = XDocument.Load(xmlLocation).Descendants("track").First();
        Cache.Insert("MostRecentTrack",
                     MostRecentTrack,
                     null,
                     DateTime.MaxValue,
                     TimeSpan.FromMinutes(10));
    }
    catch
    {
        // Catch everything so that any failure doesn't bring the website down
        MostRecentTrack = null;
    }
}

In the HTML section of your control, put the following code:

<asp:PlaceHolder ID="LatestTrackHolder" runat="server">
    <p class="LatestTrack">
        Last listened to <%= (string) MostRecentTrack.Element("name") %>
        by <%= (string) MostRecentTrack.Element("artist") %>
        (on <%= (string) MostRecentTrack.Element("date") %>)
    </p>
    <asp:Literal ID="LastFmUsername" runat="server"
                 Visible="false"
                 Text="YOUR_USERNAME_HERE" />
</asp:PlaceHolder>

This code uses System.Linq and System.Xml.Linq so don't forget to add the relevant references. Also, don't forget to put your real last.fm username in the hidden Literal in your HTML code. When you've created your control, add it to your page like this:

<%@ Register Src="~/MyUserControls/MostRecentTrack.ascx"
    TagName="MostRecentTrack" TagPrefix="lastFm" %>

<lastFm:MostRecentTrack runat="server" />

I've got it below my navigation menu on my master page, so it shows up on every page.

Add comment




  Country flag

Visual verification


biuquote
  • Comment
  • Preview
Loading