我在nodejs中创建了视频流服务器。对于视频流,我使用了范围字节流技术。但是在客户端,即在浏览器上无法呈现该视频。我在这里提供代码。这里是10mb的movie1.mp4文件。
http.createServer(function (req, res) {
if (req.url == '/movie1.mp4') {
var movie_mp4 = fs.readFileSync('movie1.mp4');
var total = movie_mp4.length;
var range = req.headers.range;
console.log("range"+range)
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var chunksize = 10000;
var end = start + chunksize; //positions[1] ? parseInt(positions[1], 10) : total - 1;
if(total < end){
end = total-1;
res.writeHead(200, { "Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": (end-start),
"Content-Type":"video/mp4"});
res.end(movie_mp4.slice(start, end), "binary");
}else{
res.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": (end-start),
"Content-Type":"video/mp4"});
res.end(movie_mp4.slice(start, end), "binary");
}
}
else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html> <title>Welcome</title> <body>' );
res.write('<video controls preload="auto"> <source src="movie1.mp4" type="video/mp4"/> </video>');
res.write('</body> </html>');
return res.end();
}
}).listen(8080);