我想使用socket.io和socket.io-stream将音频从NodeJS服务器流式传输到客户端浏览器,我成功完成了任务,只有一个问题。 首先,这是代码 server.js
const express = require("express");
const app = express();
const server = require("http").Server(app);
const port = process.env.port || 8080;
const path = require("path");
const fs = require("fs");
const io = require("socket.io")(server);
const ss = require("socket.io-stream");
app.use(express.static(path.join(__dirname, "public")));
server.listen(port, () => {
console.log(`Server listening on ${port}`);
});
io.on("connection", socket => {
socket.emit("start", { hello: "world!" });
socket.on("stream", data => {
let stream = ss.createStream();
let filename = path.join(__dirname, `/clips/Wegz.mp3`);
ss(socket).emit("audio-stream", stream, { name: filename });
fs.createReadStream(filename).pipe(stream);
});
});
client.js
var socket = io("http://localhost:" + window.location.port);
var audio = document.getElementById("audio");
socket.on("start", function(data) {
socket.emit("stream", { Data: "you can send any data back" });
ss(socket).on("audio-stream", function(stream, data) {
let parts = [];
stream.on("data", chunk => {
parts.push(chunk);
});
stream.on("end", function() {
console.log(i);
audio.src = URL.createObjectURL(new Blob(parts));
audio.play();
});
});
});
这里的问题是我将所有块都推送到列表之后播放音频,但是我想逐块同时播放音频,而不必等待所有部分被推送。 希望我澄清了我的问题,对我们的帮助将不胜感激。
答案 0 :(得分:0)
您尝试这样做吗?
stream.on("data", chunk => {
audio.src = URL.createObjectURL(new Blob(parts));
audio.play();
parts.push(chunk);
});