DEV Community

Cover image for How To Stream Mp3 With NodeJS To HTML Audio Tag
Wachira
Wachira

Posted on • Originally published at blog.bywachira.com

How To Stream Mp3 With NodeJS To HTML Audio Tag

In this article we are going to make a simple nodejs API endpoint that streams an mp3 file hosted on publicly anywhere example:

  • Amazon S3
  • Cloudinary
  • Megaphone
  • Public mp3 file

Prerequisites

  • Nodejs Basics
  • Used Axios request library
  • Express basics
  • Hosted audio

Note: This is not a scalable way to stream audio, there are better ways by handling the streaming using HLS and FFmpeg on a server somewhere. You can use this script to stream and binge your favorite podcast.

Let's get started

First, we need to setup our project:

yarn init
Enter fullscreen mode Exit fullscreen mode

Fill out the prompts or just work with the default values by adding -y argument at the end.

Next, we need to install relevant npm packages

yarn add express axios
Enter fullscreen mode Exit fullscreen mode

Let's create our endpoint

// We will use this to make HTTP request to the mp3 link
const axios = require("axios");
// adapters are axios modules that handle dispatching a request and settling a returned Promise once a response is received.
const httpAdapter = require("axios/lib/adapters/http");
// express is lightweight web framework
const express = require("express");

// Initialize express and assign to variable app
const app = express();

const INPUT =
  "https://dcs.megaphone.fm/ADV3183643348.mp3?key=c3dc25ae82cc18218902aa6a0675798a";

app.get("/audio", (req, res) => {
  axios
    .get(INPUT, { responseType: "stream", adapter: httpAdapter, 'Content-Range': 'bytes 16561-8065611'  })
    .then((Response) => {
      const stream = Response.data;

      res.set("content-type", "audio/mp3");
      res.set("accept-ranges", "bytes");
      res.set("content-length", Response.headers["content-length"]);
      console.log(Response);

      stream.on("data", (chunk) => {
        res.write(chunk);
      });

      stream.on("error", (err) => {
        res.sendStatus(404);
      });

      stream.on("end", () => {
        res.end();
      });
    })
    .catch((Err) => {
      console.log(Err.message);
    });
});

app.listen(4000, () => {
  console.log("Server is running");
});
Enter fullscreen mode Exit fullscreen mode

Continue here

Top comments (2)

Collapse
 
marcellothearcane profile image
marcellothearcane

Rather than a "continue here" link, it would be better to have all the information here too :)

Collapse
 
wchr profile image
Wachira

My blog has pretty dead for a while, but I will soon move them here