【发布时间】:2022-11-04 21:56:35
【问题描述】:
我正在使用节点后端来提供要流式传输的 mp4 视频。 此代码将视频作为一个块返回。
app.get('/video', (req, res) => {
i++;
const range = req.headers.range;
if (!range) {
res.status(400).send("Requires Range header");
}
else {
console.log(`Range = ${range}`);
}
// get video stats
const videoSize = fs.statSync(videoPath).size;
// Parse Range
// Example: "bytes=32324-"
const CHUNK_SIZE = 10 ** 6;
const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
// Create headers
const contentLength = end - start + 1;
console.log(`video hit (${i}). chunkSize=${CHUNK_SIZE}. start = ${start}. end = ${end}. contentLength = ${contentLength}, videoSize = ${videoSize}`);
const headers = {
"Content-Range": `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges": "bytes",
"Content-Length": contentLength,
"Content-Type": "video/mp4",
};
// HTTP Status 206 for Partial Content
res.writeHead(206, headers);
// create video read stream for this particular chunk
const videoStream = fs.createReadStream(videoPath, { start, end });
// console.log(videoStream);
// Stream the video chunk to the client
videoStream.pipe(res);
});
我使用 react-native-video 来播放视频。
<Video
source={{
uri: this.state.source.uri,
type: 'mp4',
headers: {
'range': bytes=0-'
}
}}
但是在播放完第一个块后它就停止了。如何加载下一个块? 我尝试将标头范围设置为大于 0 以尝试像这样加载下一个块。
headers: {
'range': 'bytes=1000-'
}
后端被正确调用, 但它在前端给出了一个错误
{"error": {"extra": -2147483648, "what": 1}}
实际上,我在搜索如何流式传输视频时发现了将视频作为块返回的代码。但我不明白使用块的意义何在,因为 react-native-video 只能从直接 url 流式传输。谁能解释我应该只使用直接 url 还是继续使用块方法并寻找解决方案?
【问题讨论】:
标签: node.js react-native