如何从谷歌获取视频流可以存储能够寻找的对象 [英] How to get a video stream from google could storage object that is able to seek

查看:57
本文介绍了如何从谷歌获取视频流可以存储能够寻找的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从express.js服务器中的云存储桶中流式传输视频文件,并且能够成功地将该流传输到前端中的视频元素.但是,由于视频内容现在是逐步加载的,因此无法浏览加载的视频.

I'm streaming a video file from a cloud storage bucket in an express.js server and was able to successfully pipe that stream to a video element in the frontend. However, since the video content is now loaded progressively, I can't seek through the loaded video.

我用于从云存储对象获取视频流的node.js代码如下.

My node.js code for getting a video stream from a cloud storage object is as follows.

async function getVideoStream(gcloudFileName,res){
  const bucket = storage.bucket(process.env.GCS_BUCKET);
  const remoteFile = bucket.file(gcloudFileName);
  return remoteFile.createReadStream().pipe(res)
}

如何使该视频流可以搜索,以便用户可以在前端的视频中搜索?非常有用的建议.

我尝试了@Rafael的答案,并在一定程度上进行了工作,但是现在的问题是,在交付了视频的前几个块之后,流停止了.同时,视频也停止播放.

I tried with @Rafael's answer and got it working up to some extent, but now the problem is the stream stops after delivering the first few chunks of the video. Also at the same time, the video also stops playing.

推荐答案

您需要使用远程请求(如@szatmary注释中所述),以便服务器可以一次发送文件的大块而不是整个文件,您可以在此文档中找到完整的说明文章,但是将其应用于您的代码,您可以执行以下操作:

You need to use ranged requests, as mentioned in @szatmary comment, so that the server can send chunks of the file at a time instead of the whole thing, you can find a complete explanation in this article, but applied to your code you can do the following:

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)
}

这篇关于如何从谷歌获取视频流可以存储能够寻找的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆