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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.