html5-通过node.js使用HTML 5进行视频流传输

我正在尝试设置一个网络服务器,该服务器将使用node.js将视频流传输到HTML5视频标签。 到目前为止,这是我的代码:

var range = request.headers.range;
var total = file.length;

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;

response.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": type });
response.end(file);

其中“ request”代表http请求,类型是“ application / ogg”或“ video / ogg”(我都尝试过),“ file”是已从文件系统读取的.ogv文件。 这是响应头:

Content-Range   bytes 0-14270463/14270464
Accept-Ranges   bytes
Content-Length   14270464
Connection     keep-alive
Content-Type     video/ogg

我已经检查了响应头,并且此代码似乎运行良好,但是存在两个问题:

  1. 该视频在本地网络上的加载速度似乎非常慢。 据我所知,使用Firebug检查响应,该文件似乎以约150 kb / sec的速度流传输。
  2. 该视频完全无法播放。 即使我等待整个加载,HTML 5视频标签也只会显示一个大的“ x”,而不是firefox中的电影。

是否有人对我可以通过node.js进行视频流传输有什么想法?

谢谢!
克里斯

Chris Harrington asked 2020-07-23T09:30:28Z
7个解决方案
24 votes

我知道这是一个非常老的问题,但是Google似乎喜欢它,所以我认为值得指出的是,我编写了一个Node.js视频流模块(Github或通过NPM),希望也值得一看。

meloncholy answered 2020-07-23T09:35:17Z
18 votes

我可以在nodejs论坛的一些帮助下使它起作用:

[HTTP://groups.Google.com/group/node将是/browse_thread/thread/8339哦0对此825从057发/822不2到底48发36哦890]

Google网上论坛主题的重点:

众所周知,谷歌浏览器会首先发出0-1024范围的请求 然后请求范围“ 1024-”。

response.end(file.slice(start,chunksize),“ binary”);

然后:

通过设置,我可以使视频在Firefox中正常播放 “连接”标头改为“关闭”

然后:

似乎您在错误地计算内容长度:

var chunksize =(end-start)+1;

如果开始为0,结束为1,在您的情况下,chunksize为2,则应该 是1。

Chris Harrington answered 2020-07-23T09:36:21Z
11 votes

该解决方案异步读取服务器端的视频或音频媒体文件...它以可见的URL启动nodejs服务器

[http:// localhost:8888 /]

也可以正确处理客户端HTML5(浏览器/应用)前进/后退UI小部件滑块的移动

将以下代码段另存为服务器端文件:

media_server.js

...使用在服务器端执行

node media_server.js

请享用

var http = require('http'),
    fs = require('fs'),
    util = require('util');

var path = "/path/to/local/video/or/audio/file/on/server.mp4";

var port = 8888;
var host = "localhost";

http.createServer(function (req, res) {

  var stat = fs.statSync(path);
  var total = stat.size;

  if (req.headers.range) {   // meaning client (browser) has moved the forward/back slider
                                         // which has sent this request back to this server logic ... cool
    var range = req.headers.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;
    console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);

    var file = fs.createReadStream(path, {start: start, end: end});
    res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
    file.pipe(res);

  } else {

    console.log('ALL: ' + total);
    res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
    fs.createReadStream(path).pipe(res);
  }
}).listen(port, host);

console.log("Server running at http://" + host + ":" + port + "/");
Scott Stensland answered 2020-07-23T09:37:03Z
5 votes

根据Sam9291的回答,我使用createReadStream()重写了该函数并解决了一些问题:

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

  });

}
Udo G answered 2020-07-23T09:37:23Z
4 votes

我在Node.js之上使用MVC框架sails.js,并设法通过以下代码使其正常工作:

/**
 * VideoController
 *
 * @module      :: Controller
 * @description :: Contains logic for handling requests.
 */

 var fs = require('fs');

module.exports = {

  /* e.g.
  sayHello: function (req, res) {
    res.send('hello world!');
  }
  */

  /**
   * /video/stream
   */ 
  stream: function (req,res) {

    // This will render the view: 
    // C:\Users\sam\Documents\Dev\Fun\mymoviebank/views/video/stream.ejs
    res.view();

  },

  play: function (req,res) {

    fs.readFile('/Users/sam/Videos/big_buck_bunny.mp4', function (err, data) {
      if (err) throw err;

      var range = req.headers.range;
        var total = data.length;

        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;

        res.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": 'video/mp4' });
        res.end(data);

    });

  }

};

希望这可以帮助

Samuel Poirier answered 2020-07-23T09:42:21Z
3 votes

我发现此解决方案似乎更简单,并且(与已确认的答案不同)对我有用。 (我尝试在该线程的末尾改编coffeescript解决方案,并且一旦我处理了最初的请求(“ bytes = 0-”)将其分解的事实,它就可以工作。

[HTTP://elegant code.com/2011/04/06/taking-baby-steps-with-node-就是-pumping-data-between-streams/]

我的实际实现:

function stream_response( res, file_path, content_type ){
    var readStream = fs.createReadStream(file_path);

    readStream.on('data', function(data) {
        var flushed = res.write(data);
        // Pause the read stream when the write stream gets saturated
        console.log( 'streaming data', file_path );
        if(!flushed){
            readStream.pause();
        }
    });

    res.on('drain', function() {
        // Resume the read stream when the write stream gets hungry 
        readStream.resume();
    });

    readStream.on('end', function() {
        res.end();
    });

    readStream.on('error', function(err) {
        console.error('Exception', err, 'while streaming', file_path);
        res.end();
    });

    res.writeHead(200, {'Content-Type': content_type});
}
podperson answered 2020-07-23T09:42:50Z
0 votes

使用Express时,请将其放入您的media_server.js或index.js中,这将在端口3000上为媒体提供服务

const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.html'))
})

app.get('/video', function(req, res) {
  const path = 'assets/sample.mp4'// your video path
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const range = req.headers.range

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
      ? parseInt(parts[1], 10)
      : fileSize-1

    const chunksize = (end-start)+1
    const file = fs.createReadStream(path, {start, end})
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    }

    res.writeHead(206, head)
    file.pipe(res)
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)
  }
})

app.listen(3000, function () {
  console.log('Listening on port 3000!')
})

然后在您的index.html中

<html>
  <head>
    <title>Video stream sample</title>
  </head>
  <body>
    <video id="videoPlayer" controls muted="muted" autoplay> 
      <source src="http://localhost:3000/video" type="video/mp4">
    </video>
  </body>
</html>
Kevin Muchwat answered 2020-07-23T09:43:15Z
translate from https://stackoverflow.com:/questions/4360060/video-streaming-with-html-5-via-node-js