视频流html5播放器,javascript – 使用Node.js将视频文件流式传输到html5视频播放器,以便视频控件继续工作?...

Tl; Dr – 问题:

什么是正确的方式来处理流视频文件到具有Node.js的html5视频播放器,以便视频控件继续工作?

我认为它与头处理的方式有关。无论如何,这里的背景信息。代码有点冗长,但是,它很简单。

使用Node将小视频文件流式传输到HTML5视频很容易

客户:

Welcome

Your browser does not support the video element.

服务器:

// Declare Vars & Read Files

var fs = require('fs'),

http = require('http'),

url = require('url'),

path = require('path');

var movie_webm, movie_mp4, movie_ogg;

// ... [snip] ... (Read index page)

fs.readFile(path.resolve(__dirname,"movie.mp4"), function (err, data) {

if (err) {

throw err;

}

movie_mp4 = data;

});

// ... [snip] ... (Read two other formats for the video)

// Serve & Stream Video

http.createServer(function (req, res) {

// ... [snip] ... (Serve client files)

var total;

if (reqResource == "/movie.mp4") {

total = movie_mp4.length;

}

// ... [snip] ... handle two other formats for the video

var range = req.headers.range;

var positions = range.replace(/bytes=/, "").split("-");

var start = parseInt(positions[0], 10);

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

var chunksize = (end - start) + 1;

if (reqResource == "/movie.mp4") {

res.writeHead(206, {

"Content-Range": "bytes " + start + "-" + end + "/" + total,

"Accept-Ranges": "bytes",

"Content-Length": chunksize,

"Content-Type": "video/mp4"

});

res.end(movie_mp4.slice(start, end + 1), "binary");

}

// ... [snip] ... handle two other formats for the video

}).listen(8888);

但是这种方法限于文件< 1GB大小。 使用fs.createReadStream流式(任何大小)视频文件 通过使用fs.createReadStream(),服务器可以读取流中的文件,而不是一次性将其全部读入内存。这听起来像做正确的方法,语法是非常简单: 服务器代码段:

movieStream = fs.createReadStream(pathToFile);

movieStream.on('open', function () {

res.writeHead(206, {

"Content-Range": "bytes " + start + "-" + end + "/" + total,

"Accept-Ranges": "bytes",

"Content-Length": chunksize,

"Content-Type": "video/mp4"

});

// This just pipes the read stream to the response object (which goes

//to the client)

movieStream.pipe(res);

});

movieStream.on('error', function (err) {

res.end(err);

});

这流视频很好!但视频控件不再工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值