gpt4 book ai didi

html - 使用 nodejs 将视频流式传输到浏览器

转载 作者:行者123 更新时间:2023-11-28 03:14:02 25 4
gpt4 key购买 nike

我想使用 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 - 使用 nodejs 将视频流式传输到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com