我正在尝试使用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请求,type是“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
我已经检查了响应标头,这段代码看起来运行正常,但是有一些问题:
有没有人有任何想法,我可以做什么来通过node.js使视频流工作?
谢谢! 克里斯
我知道这是一个非常古老的问题,但是谷歌似乎喜欢它,我认为值得指出我写了一个Node.js video streaming module(Github,或通过NPM),希望值得一看。
我能够在nodejs论坛的帮助下使用它:
http://groups.google.com/group/nodejs/browse_thread/thread/8339e0dc825c057f/822b2dd48f36e890
Google网上论坛帖子的亮点:
众所周知,Google Chrome首先发出0-1024范围的请求,然后请求范围“1024-”。
response.end(file.slice(start,chunksize),“binary”);
然后:
通过将“连接”标题设置为“关闭”,我能够在Firefox中播放视频没有问题
然后:
似乎您错误地计算了内容长度:
var chunksize =(end-start)+1;
如果start为0且end为1,则在你的情况下chunksize为2,它应为1。
此解决方案执行服务器端视频或音频媒体文件的异步读取...它会在可见的URL处旋转nodejs服务器
它还正确处理客户端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 + "/");
基于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);
});
}
我在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);
});
}
};
希望这可以帮助
我发现这个解决方案似乎更简单(并且与检查的答案不同)对我有用。 (我尝试在该线程结束时调整coffeescript解决方案,一旦我处理了初始请求(“bytes = 0-”)将其炸毁的事实,它就有用了。
http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-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});
}
当使用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>