Pav*_*ndu 5 video-streaming node.js google-cloud-storage
我正在从express.js 服务器中的云存储桶流式传输视频文件,并且能够成功将该流传输到前端中的视频元素。但是,由于视频内容现在是渐进加载的,因此我无法搜索加载的视频。
我用于从云存储对象获取视频流的 Node.js 代码如下。
async function getVideoStream(gcloudFileName,res){
const bucket = storage.bucket(process.env.GCS_BUCKET);
const remoteFile = bucket.file(gcloudFileName);
return remoteFile.createReadStream().pipe(res)
}
Run Code Online (Sandbox Code Playgroud)
如何使该视频流可以被搜索,以便用户可以在前端搜索视频? 非常感谢有用的建议。
编辑:
我尝试了@Rafael的答案并在一定程度上得到了它的工作,但现在的问题是在交付视频的前几个块后流停止了。与此同时,视频也停止播放。
您需要使用范围请求,如 @szatmary 评论中所述,以便服务器可以一次发送文件的块而不是整个文件,您可以在本文中找到完整的解释,但应用到您的代码中您可以请执行下列操作:
async function getVideoStream(req,res){
const range = req.headers.range;
if (!range) {
res.status(400).send("Requires Range header");
}
const bucket = storage.bucket(process.env.GCS_BUCKET);
// I added the file name to your request's body
const remoteFile = bucket.file(req.body);
//calculates the chunck to be sent based on the video size
const videoSize = remoteFile.getMetadata().size;
const CHUNK_SIZE = 10 ** 6; // 1MB
const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
// Create headers
const contentLength = end - start + 1;
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);
//returns the chunk that you want
return remoteFile.createReadStream({ start, end }).pipe(res)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1916 次 |
| 最近记录: |