Ayushman Kumar
Ayushman Kumar

Reputation: 133

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

Upvotes: 0

Views: 1689

Answers (2)

Kartik Narang
Kartik Narang

Reputation: 201

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>

Upvotes: 1

Related Questions