我如何选择流中的特定块来使用 Axios 和 nodejs

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

所以我创建了一个快速服务器来将音频流式传输到 HTML 文档中的 <audio> 标签,音频流式传输没有问题,但我无法 select 中的特定点如果我这样做,音频将停止播放,除非我将所有块加载到那个点。

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>

我是 Axios 新手,所以我不知道如何发送特定块并将其投放到音频标签上。

由于您正在使用 Axios,当 responseType = 'stream' 它 returns 您是一个流。 您需要做的就是通过将 axiosResponse.data.pipe(res); 放在第一个 then 函数中将其“连接”到响应,如下所示:

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");
});