【问题标题】:Streaming video using nodejs to the browser使用 nodejs 将视频流式传输到浏览器
【发布时间】:2015-05-22 10:12:01
【问题描述】:

我想使用 nodejs 创建一个流媒体服务器(我知道有很多但我想使用 nodejs 创建一个),问题是视频没有像在 youtube 上那样被下载,你能告诉我如何要做像 youtube 这样的流媒体,谢谢

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

http.createServer(function (req, res) {
var path = '/home/flumotion/test.mp4';
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers['range']) {
    var range = req.headers.range; 
    console.log("Range = "+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(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

【问题讨论】:

  • 可能值得一看这个问答:stackoverflow.com/questions/24976123/…
  • 谢谢,但在我的情况下控件可以正常工作
  • 也许我误解了你的问题,但我相信这个答案包含一个流媒体服务器的工作示例(我自己还没有实际尝试过)。
  • 是的,它确实,但与 youtube 的方式不同,不是每个时间间隔都发送请求
  • 我认为更详细地解释这个问题可能会更好 - 我不太确定问题或这些 cmets 是否清楚。

标签: html node.js streaming video-streaming


【解决方案1】:

发送 206 而不是 200 对我有用

var range = req.headers.range;
var total = data.length;// your video size.. you can use fs.statSync("filename").size to get the size of the video if it is stored in a file system 
split = range.split(/[-=]/),
ini = +split[1],
end = split[2]?+split[2]:total-1,
chunkSize = end - ini + 1;

res.writeHead(206, {
    "Content-Range": "bytes " + ini + "-" + end + "/" + total,
    "Accept-Ranges": "bytes",
    "Content-Length": chunkSize,
    "Content-Type": // check mimeType
});

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2016-05-30
    • 2017-04-01
    • 2018-03-13
    • 2010-09-14
    • 2019-08-18
    相关资源
    最近更新 更多