Erick Wachira
Erick Wachira

Reputation: 85

How do I choose a particular chunk in a stream to play with Axios and nodejs

So I created an express server to stream audio to an <audio> tag in the HTML document, The audio is streaming with no issues but I cannot select a particular point in the audio if I do so it stops playing unless I loaded the all the chunks to that point.

index.html

const axios = require("axios");
const httpAdapter = require("axios/lib/adapters/http");
const fs = require("fs");
const express = require("express");

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 })
    .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");
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node Streaming prototype</title>
</head>
<body>
    <audio controls src="http://localhost:4000/audio"></audio>
</body>
</html>

I am new to Axios so I don't know how I can send a particular chunk and serve it on the audio tag.

Upvotes: 1

Views: 1612

Answers (1)

felixmosh
felixmosh

Reputation: 35513

Since you are using Axios, when responseType = 'stream' it returns you a stream. All you need to do is to "connect" it to the response by putting axiosResponse.data.pipe(res); in the first then function, like below:

const axios = require("axios");
const httpAdapter = require("axios/lib/adapters/http");
const fs = require("fs");
const express = require("express");

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 })
    .then((axiosResponse) => {
      const stream = axiosResponse.data;

      res.set("content-type", "audio/mp3");
      res.set("accept-ranges", "bytes");
      res.set("content-length", Response.headers["content-length"]);
      stream.pipe(res); // <---- pipe the stream to the response
    })
    .catch((Err) => {
      console.log(Err.message);
    });
});

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

Upvotes: 3

Related Questions