我想用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/');

最佳答案

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

关于html - 使用Node.js将视频流式传输到浏览器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29142179/

10-11 10:27