Video streaming with HTML 5 via node.js

后端 未结 8 1937
青春惊慌失措
青春惊慌失措 2020-11-30 18:01

I\'m trying to set up a web server that will support streaming video to an HTML5 video tag using node.js. Here\'s my code so far:

var range = request.header         


        
相关标签:
8条回答
  • 2020-11-30 18:50

    I know this is a really old question, but as Google seems to like it I thought it would be worth pointing out that I wrote a Node.js video streaming module (Github, or via NPM) that's hopefully worth a look too.

    0 讨论(0)
  • 2020-11-30 18:50

    Based on Sam9291's answer, I rewrote the function using createReadStream() and fixing some problems:

    /**
     * Sends a static file to the HTTP client, supporting partial transfers.
     * 
     * @req HTTP request object
     * @res HTTP response object
     * @fn Path to file that should be sent
     * @contentType MIME type for the response (defaults to HTML)
     */      
    function sendFile(req, res, fn, contentType) {
    
      contentType = contentType || "text/html";
    
      fs.stat(fn, function(err, stats) {
        var headers;
    
        if (err) {
          res.writeHead(404, {"Content-Type":"text/plain"});
          res.end("Could not read file");
          return;
        }
    
        var range = req.headers.range || "";    
        var total = stats.size;
    
        if (range) {
    
          var parts = range.replace(/bytes=/, "").split("-");
          var partialstart = parts[0];
          var partialend = parts[1];
    
          var start = parseInt(partialstart, 10);
          var end = partialend ? parseInt(partialend, 10) : total-1;
    
          var chunksize = (end-start)+1;
    
          headers = { 
            "Content-Range": "bytes " + start + "-" + end + "/" + total, 
            "Accept-Ranges": "bytes", 
            "Content-Length": chunksize, 
            "Content-Type": contentType 
          };
          res.writeHead(206, headers);
    
        } else {
    
          headers = { 
            "Accept-Ranges": "bytes", 
            "Content-Length": stats.size, 
            "Content-Type": contentType 
          };
          res.writeHead(200, headers);
    
        }
    
        var readStream = fs.createReadStream(fn, {start:start, end:end});
        readStream.pipe(res);    
    
      });
    
    }
    
    0 讨论(0)
提交回复
热议问题