Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

node.js - How do I stream video using Node JS and Use it in my Django Project?

I am working on a Django project related to Video Streaming. All my basic functionalities(like Authentication, login, etc.) are being made using Django. Now I want to Stream Video on my Web App.

I didn't find a solution to Stream my videos directly using Django. So, I decided to stream my video using Node.js and integrate this feature in my Django Project.

Here is the Node-Express Code I used for Streaming my Videos in my frontend.

    app.get("/video", function (req, res) {
  
  const range = req.headers.range;
  if (!range) {
    res.status(400).send("Requires Range header");
  }

  
  const videoPath = "mySample.mp4";
  const videoSize = fs.statSync("mySample.mp4").size;

  
  const CHUNK_SIZE = 10 ** 6; // 1MB
  const start = Number(range.replace(/D/g, ""));
  const end = Math.min(start + CHUNK_SIZE, videoSize - 1);

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

  
  const videoStream = fs.createReadStream(videoPath, { start, end });

  
  videoStream.pipe(res);
});

If someone can tell me how can I integrate this with my Django Project.

Thanks :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply use the Node API landing point as the source URL in your HTML template.

This is how I displayed the video in my ReactJS app, but it should work in simple HTML page too.

<video controls>
    <source
       id="hi"
       src="http://localhost:5001/****/video" // this url was the node API
     />
 </video>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...