Build a now-playing widget for a livestream

Show the currently-playing song on a livestream overlay using AudD audio streams, with a webhook callback receiver or longpoll, plus a copy-paste HTML widget.

7 min read View as Markdown
On this page

You can use the AudD real-time music recognition service for audio streams to identify the songs that are being played on your livestream (a Twitch DJ set, a YouTube radio channel, an Icecast web radio, or any other stream). When a song starts on your stream, your backend receives a callback (a POST request from our servers) with the artist, the title and the song link. In this recipe, you’ll add a widget that shows the song, with its cover, on top of the video.

What you’ll build

There are 3 parts:

  1. The stream. The stream is the URL you send us once. We support most of the stream formats, including DASH, Icecast, HLS, m3u/m3u8, and we also natively support Twitch broadcasts and YouTube live streams.
  2. The backend. It receives the callbacks and keeps the latest song for each stream (callbacks are the recommended method). If we can’t connect to your server, it can use longpoll instead. This recipe shows both.
  3. The widget. This widget will display the currently playing song and its cover art, on top of the video in OBS or on a web page.

All the streams API methods are on https://api.audd.io/. By default, we will send new results after songs end playing, with the total played time. Use callbacks=before if you want to get the results when songs start playing: that’s what you need for a live now-playing display.

Prerequisites

  • You can get a token from our API Dashboard. Set the limit of audio streams and pay on the API Dashboard. The music recognition costs $45 per audio stream per month with our music DB.
  • The test token doesn’t work for streams; use your own token.
  • The code requires Node.js 20 or later, the official SDK and Express: npm install @audd/sdk express
  • A stream to recognize. For a quick test, as the URL of the audio stream, you can simply send the URL of a public radio stream, like https://npr-ice.streamguys1.com/live.mp3.

Walkthrough

Step 1: Set the account callback URL (once)

There is no per-stream callback URL: the callbacks from all your streams will be sent to the specified URL as JSON in a POST request. Set it once, before you add any streams.

TypeScript
import { AudD } from "@audd/sdk";

const audd = new AudD(process.env.AUDD_API_TOKEN!); // dashboard.audd.io

await audd.streams.setCallbackUrl(
  "https://your-app.example.com/audd-callback",
  { returnMetadata: ["apple_music", "spotify"] }, // adds streaming links
);

returnMetadata is optional: it adds Apple Music and Spotify metadata to the callbacks. The cover doesn’t need it: each result from our music DB has a songLink (a lis.tn song page), and adding ?thumb to the end of that URL gives the cover image, as the widget below does.

Even if you only plan to longpoll, the account still needs a callback URL. Otherwise, the poll returns no results. If you don’t have a server, set https://audd.tech/empty/ as the callback URL: it always responds with 200 OK.

TypeScript
await audd.streams.setCallbackUrl("https://audd.tech/empty/");

Step 2: Add your stream

Add the stream using streams.add (the addStream API method). As the radioId, send any integer that will identify this stream for you. You can tell the streams apart by the radioId in every match: the integer you passed to streams.add.

TypeScript
const radioId = 1; // your handle for this stream

// A direct stream URL:
await audd.streams.add({
  url: "https://npr-ice.streamguys1.com/live.mp3",
  radioId,
  callbacks: "before", // deliver at song START — best for "now playing"
});

We also natively support Twitch broadcasts and YouTube live streams, and you can send twitch:[channel name], youtube:[video id], and youtube-ch:[channel id] as the URL instead of a raw media URL:

TypeScript
// Twitch channel:
await audd.streams.add({ url: "twitch:monstercat", radioId: 2, callbacks: "before" });

// YouTube video id (from youtube.com/watch?v=5qap5aO4i9A):
await audd.streams.add({ url: "youtube:5qap5aO4i9A", radioId: 3, callbacks: "before" });

// YouTube channel's current live stream:
await audd.streams.add({ url: "youtube-ch:UC3zwjSYv4k5HKGXCHMpjVRg", radioId: 4, callbacks: "before" });

Use audd.streams.setUrl(radioId, url) to update the URL of a stream, audd.streams.delete(radioId) to delete a stream, and audd.streams.list() to get all the streams.

With before, you won’t receive the total played time in the callbacks, which a now-playing widget doesn’t need.

To be able to receive callbacks from AudD, your server needs to be accessible from the web. You’ll receive callbacks with results and with notifications. handleCallback returns the result (match) or the notification, so you don’t check status by hand.

TypeScript
import express from "express";
import { handleCallback } from "@audd/sdk";

const app = express();
app.use(express.json());

// In-memory "current song" per stream. Use Redis in production.
const nowPlaying = new Map<number, unknown>();

app.post("/audd-callback", async (req, res) => {
  try {
    const { match, notification } = await handleCallback(req);
    if (match?.song && match.radioId !== undefined) {
      const s = match.song;
      nowPlaying.set(match.radioId, {
        artist: s.artist,
        title: s.title,
        cover: s.songLink ? `${s.songLink}?thumb` : null, // lis.tn cover-art
        songLink: s.songLink, // universal lis.tn link
        at: Date.now(),
      });
    } else if (notification) {
      // 650 = can't connect to the stream; 651 = only white noise
      console.warn("stream", notification.notificationCode, notification.notificationMessage);
    }
    res.sendStatus(200); // 200 for every valid callback — see note below
  } catch (err) {
    console.error("bad callback body", err);
    res.sendStatus(400);
  }
});

// The widget polls this:
app.get("/now-playing/:radioId", (req, res) => {
  res.set("Access-Control-Allow-Origin", "*"); // the widget loads from another origin
  res.json(nowPlaying.get(Number(req.params.radioId)) ?? null);
});

app.listen(8080);

The server keeps the latest song for each radioId, and /now-playing/1 returns it to the widget as JSON.

Always respond 200 OK to a callback. If your server doesn’t respond to the callbacks with the 200 OK status or we can’t connect to your server, we’ll put the callbacks in a queue. When your server is back online, we’ll gradually send all the backlog, so the matches are delayed, not lost.

Step 3b: Receive matches with longpoll (no public server)

If we can’t connect to your server (a laptop, or a machine behind NAT), use longpoll. The SDK sends GET requests to https://api.audd.io/longpoll/, and we send the response when an event is ready or when the timeout has elapsed. Keep the /now-playing/:radioId route from Step 3a in the same process for the widget.

TypeScript
const radioId = 1;

const poll = await audd.streams.longpoll({ radioId, timeout: 50 });

for await (const m of poll.matches) {
  console.log("now playing:", m.song?.artist, "—", m.song?.title);
  // update the same nowPlaying cache your widget reads
}

The longpoll() method returns a poll object and performs the polling in the background. Use this object’s properties to get the matches (poll.matches), the notifications (poll.notifications) and the error that stops the poll (poll.errors). Call poll.close() to stop it. timeout is how many seconds to wait for an event (50 by default). longpoll() checks that the account has a callback URL (see Step 1) and throws an AudDInvalidRequestError if it doesn’t. The code uses your API token, so run it on your own machine, never in a browser. A browser can subscribe with the stream’s longpoll category (longpollCategory from audd.streams.list(), passed from your server) through LongpollConsumer from @audd/sdk/longpoll (see the Node.js SDK docs), or use the hosted widget.

Step 4: The widget

When the widget opens, and then every 5 seconds, it asks your backend’s /now-playing/:radioId for the current song, and it updates the page when the song changes.

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Now Playing</title>
  <style>
    body { margin: 0; background: transparent; font-family: system-ui, sans-serif; }
    .np {
      display: flex; align-items: center; gap: 14px;
      padding: 12px 16px; border-radius: 12px;
      background: rgba(0,0,0,.65); color: #fff; width: max-content;
      box-shadow: 0 4px 20px rgba(0,0,0,.4);
    }
    .np img { width: 56px; height: 56px; border-radius: 8px; object-fit: cover; }
    .np .meta { line-height: 1.3; }
    .np .title { font-weight: 600; font-size: 16px; }
    .np .artist { opacity: .85; font-size: 14px; }
    .np.hidden { display: none; }
  </style>
</head>
<body>
  <div id="np" class="np hidden">
    <img id="cover" alt="" />
    <div class="meta">
      <div id="title" class="title"></div>
      <div id="artist" class="artist"></div>
    </div>
  </div>

  <script>
    const BACKEND = "https://your-app.example.com"; // your Step 3 server
    const RADIO_ID = 1;
    const POLL_MS = 5000;

    const el = {
      box: document.getElementById("np"),
      cover: document.getElementById("cover"),
      title: document.getElementById("title"),
      artist: document.getElementById("artist"),
    };
    let current = null;

    async function tick() {
      try {
        const res = await fetch(`${BACKEND}/now-playing/${RADIO_ID}`);
        const song = await res.json();
        if (!song) { el.box.classList.add("hidden"); current = null; return; }
        const key = `${song.artist} - ${song.title}`;
        if (key === current) return; // unchanged
        current = key;
        el.title.textContent = song.title ?? "";
        el.artist.textContent = song.artist ?? "";
        if (song.cover) { el.cover.src = song.cover; el.cover.style.display = ""; }
        else { el.cover.style.display = "none"; }
        el.box.classList.remove("hidden");
      } catch (e) {
        console.error("poll failed", e);
      }
    }

    tick();
    setInterval(tick, POLL_MS);
  </script>
</body>
</html>

Embedding in OBS. Save the code as widget.html and add it to OBS as a Browser source (the local file, or the URL of the hosted page). Set its width and height to fit the overlay. The page has no background, so it can be placed on top of the video. If you don’t want to build a frontend, you can also use our widget (see Going further).

What you get back

The format of a callback with a result is below. The SDK parses it into a StreamCallbackMatch.

JSON
{
  "status": "success",
  "result": {
    "radio_id": 1,
    "timestamp": "2020-04-13 10:31:43",
    "play_length": 111,
    "results": [
      {
        "artist": "Alan Walker, A$AP Rocky",
        "title": "Live Fast (PUBGM)",
        "album": "Live Fast (PUBGM)",
        "release_date": "2019-07-25",
        "label": "MER Recordings",
        "score": 100,
        "song_link": "https://lis.tn/LiveFastPUBGM"
      }
    ]
  }
}

result contains the radio_id you chose for the stream, the timestamp of the recognition and (by default) the played duration in play_length; with callbacks=before, you won’t receive it. results contains the recognized songs: the widget shows the artist and the title of results[0] (there’s also the album). song_link links to a lis.tn song page, and score is the confidence of the match, 0–100. With returnMetadata, each song also has apple_music and spotify blocks with the streaming URLs and IDs. Fields without a typed property are in match.song?.extras.

Notifications are information about the state of the streams. If something happens to an audio stream, we’ll let you know by sending a notification so you can fix the stream or change its URL. There are 3 codes: 0 (which means that everything’s fine), 650 (which means that we can’t connect to the stream) and 651 (which means that we don’t receive any music from the stream, only white noise).

Handling errors

There are 5 kinds of errors you might see in a now-playing widget:

  • AudDAuthenticationError: Raised when the API token is not valid (e.g. a wrong or missing token, or a disabled token). Fail at startup.
  • AudDQuotaError or AudDStreamLimitError from streams.add: Raised when your account has no free stream slots: you’ve reached your limit of audio streams, or haven’t set one yet. Set or raise it on the API Dashboard.
  • AudDInvalidRequestError: Raised most often if no callback URL is set when you start longpoll. Please set the callback URL to an actual URL that can receive POST requests, or to https://audd.tech/empty/, and retry.
  • Notifications 650 and 651 (not exceptions): Fix the stream, or change its URL with setUrl.
  • AudDConnectionError: Raised when the request failed for a network-specific reason (e.g. a timeout, or a dropped connection). If a request fails three times in a row, the poll closes and the error is on poll.errors: call longpoll() again. If we can’t connect to your server, we’ll put the callbacks in a queue.
TypeScript
import { AudDInvalidRequestError } from "@audd/sdk";

try {
  const poll = await audd.streams.longpoll({ radioId: 1 });
  // ...
} catch (err) {
  if (err instanceof AudDInvalidRequestError) {
    // almost always: no callback URL on the account
    await audd.streams.setCallbackUrl("https://audd.tech/empty/");
  } else {
    throw err;
  }
}

Going further

  • No-code widget. You can also use our widget, https://widget.audd.tech/?ch=-<category>&background&history&shadow. It uses longpoll, and shows the last recognized song and, with history, the songs before it. Use the longpoll category with ”-” before it as the ch URL parameter. As the category, use the longpollCategory field from audd.streams.list(). You can share the categories with your clients or users, but please don’t include your API tokens in the client-side software.
  • Multiple streams on one overlay. The server above already keeps the last song for each radio_id; set RADIO_ID in the widget to pick the stream.
  • History strip. To show a “recently played” list, keep the last N songs for each stream instead of just the current one.
  • Your own catalog. If you have your own content that you want to recognize instead of using our music DB (160 million songs), see Public database vs. your custom catalog.

Related

Reading this as an AI agent? The raw Markdown is at recipes/now-playing-widget.md, and the full index is /resources/llms.txt.