有没有一种方法可以通过浏览器可查找(可快速转发)的方式将文件数据传输给用户
我正在向我的 CDN 之一发出请求,请求文件的数据可以是 mp4 或 mp3。然后,我在网络服务器上处理该数据,并尝试将其作为视频或音频文件发送到客户端。然而我的问题是,我找不到一种方式来发送数据,使浏览器能够快进视频/音频,当我尝试实现它时,有很多错误,有些视频无法工作。我相信这是因为我没有指定从流发送的范围,因此每次浏览器请求音频的不同部分时它都会重新发送相同的内容。
当前代码:
const range = req?.headers?.["range"] || "bytes=0-";
if (!range) {
return res.status(400).send({ err: "Requires range header"});
}
let responses = await func.render(req);
let CHUNK_SIZE = 10 ** 6;
let start = Number(range.replace(/\D/g, ""));
let end = Math.min(start + CHUNK_SIZE, responses?.size - 1);
res.setHeader("Content-Range", `bytes ${start}-${end}/${responses?.size}`);
res.setHeader("Accept-Ranges", "bytes")
res.setHeader("Content-Length", end - start + 1);
res.setHeader("Content-Type", responses?.type);
res.status(206);
responses?.stream?.pipe(res)
我能想到的唯一方法是,是否有一种方法可以从流中选择字节范围,并仅通过管道传输返回的数据的某一部分,就像 fs 可以做的那样 fs.createReadStream("path", { startByte, endByte }) 但是我不知道该怎么做
I am making a request to one of my cdn's to request the data for a file could be mp4 or mp3. I am then processing that data on my web server and trying to send it to the client as video or audio file. however my issue has been that i cannot find a way to send the data in a way that the browser is able to fast forward the video/audio and when i tried implementing it there are many bugs and some videos dont work. I believe this is because i am not specifying a range to send from the stream so it just resends the same thing every time the browser makes a request for a different part of the audio.
current code:
const range = req?.headers?.["range"] || "bytes=0-";
if (!range) {
return res.status(400).send({ err: "Requires range header"});
}
let responses = await func.render(req);
let CHUNK_SIZE = 10 ** 6;
let start = Number(range.replace(/\D/g, ""));
let end = Math.min(start + CHUNK_SIZE, responses?.size - 1);
res.setHeader("Content-Range", `bytes ${start}-${end}/${responses?.size}`);
res.setHeader("Accept-Ranges", "bytes")
res.setHeader("Content-Length", end - start + 1);
res.setHeader("Content-Type", responses?.type);
res.status(206);
responses?.stream?.pipe(res)
The only way i can think of is if somehow there is a way to select byte ranges from the stream and pipe only a certain part of the data being returned kindof like how fs can do fs.createReadStream("path", { startByte, endByte }) however i have no idea how to do this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
想通了。只需安装一个名为 range-stream 的库,然后指定我想要从流中通过管道传输的范围,然后通过管道传输它。
npm i range-stream requests?.stream?.pipe(StreamRange(start, end)).pipe(res);
这修复了它。
Figured it out. just had to install a library called range-stream and then specify the range i want to pipe from the stream and then pipe that.
npm i range-stream responses?.stream?.pipe(StreamRange(start, end)).pipe(res);
This fixed it.