Click anywhere to close

How to add Currently Playing to your homepage

I’ve used last.fm off and on for most of my music listening life. At the time of writing I have scrobbled 51,000 tracks over 15 years. For me it’s a great way to feel connected to the music I listen to over my life, and keep a much more useful history than the basic playcount & wrapped that spotify provides. If you use spotify, it’s hilariously easy to configure scrobbling, you just hit connect and authorize last.fm to pull your currently listening directly from them. I highly suggest it for anyone who listens to music (literally everyone) and likes to dig through charts/graphs about their life.

Something I’ve wanted to do forever, and as part of a recent effort to use this blog more often, is add some last.fm data to my homepage. On the homepage now you should hopefully see a Music section, that features my top 3 tracks this week, and (if I am awake) the song I am listening to right now. I’m also sharing the code on here incase anyone else wants to do this. It’s pretty shit code, but for only an hour of work I think it’s fine :).

You’ll need an API Key, which you can get for free on this page.

Lastfm Currently Playing Screenshot from Homepage

const API_KEY = "YOUR API KEY HERE";
const USERNAME = "YOUR LASTFM USERNAME HERE";

function urlencode(obj) {
    var str = [];
    for (var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
}

$(document).ready(function () {
    function displayMusic() {
        $("#music").show()
    }

    function lastfmRequest(method, params) {
        params['api_key'] = API_KEY;
        params['format'] = "json";

        return fetch("https://ws.audioscrobbler.com/2.0/?method=" + method + "&" + urlencode(params) + "&format=json")
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Network response was not ok.');
            });
    }

    function getImage(trackinfo) {
        return lastfmRequest("track.getInfo", { autocorrect: 1, track: trackinfo["name"], artist: trackinfo["artist"]["name"] })
            .then((data) => {
                    try {
                        return data.track.album.image[1]["#text"];
                    } catch(e) {
                        throw new Error("No image found")
                    }
                });
    }

    lastfmRequest("user.gettoptracks", { user: USERNAME, limit: "3", period: "7day" }).then((data) => {
        var html = '<h3 class="colorchanger">Top This Week</h2>';
        $.each(data.toptracks.track, function (i, item) {
            const itemid = item.mbid;

            html += '<div class="music-row">';
            html += '<img id="' + itemid + '" src="' + item.image[1]["#text"] + '">';
            html += '<div><a href="' + item.url + '" target="_blank">' + item.name + '</a> - ' + item.artist['name'] + '</div></div>';

            getImage(item).then((img) => {
                $("#" + itemid).attr("src", img);
            });
        });
        displayMusic();
        $('#listening-to').append(html);
    });

    lastfmRequest("user.getrecenttracks", { user: USERNAME, limit: 1 }).then((data) => {
        console.log(data);

        var item = data.recenttracks.track[0];
        if (!item["@attr"] || !item["@attr"].nowplaying) {
            return;
        }

        let html = '<h3 class="colorchanger">Now Playing</h2>';

        const itemid = item.mbid;

        html += '<div class="music-row">';
        html += '<img id="' + itemid + '" src="' + item.image[1]["#text"] + '">';
        html += '<div><a href="' + item.url + '" target="_blank">' + item.name + '</a> - ' + item.artist['#text'] + '</div></div>';

        getImage({ name: item["name"], artist: { name: item["artist"]["#text"] } }).then((img) => {
            $("#" + itemid).attr("src", img);
        });

        displayMusic();
        $('#currently-playing').append(html);

    });
});

If you end up adding this to your site please reach out :) mdl0394@gmail.com







Recent Posts

rough draft 2: falling in love by being radically honest processing my broken state trying to understand why a past relationship fucked me up so badly
Personal
posted: August 29, 2024
Farewell to Arkansas St a farewell letter to the best apartment I have ever had
Personal
posted: July 01, 2024
A quick teardown of the NES Zapper Lightgun A quick teardown of the NES Zapper Lightgun, mostly as a love letter to the geniuses who built this and a girl I will always love
Technology
posted: April 26, 2024
shouldibreaknocontact.com I have too much money, and I like to buy novelty domains
Personal
posted: March 28, 2024
How to add Currently Playing to your homepage A code snippet to add a last.fm based currently playing section to your personal site
Technology
posted: February 05, 2024