通过 node.js 使用 HTML 5 进行视频流传输 [英] Video streaming with HTML 5 via node.js

查看:47
本文介绍了通过 node.js 使用 HTML 5 进行视频流传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个 Web 服务器,该服务器将支持使用 node.js 将视频流式传输到 HTML5 视频标签.到目前为止,这是我的代码:

I'm trying to set up a web server that will support streaming video to an HTML5 video tag using node.js. Here's my code so far:

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请求,类​​型是application/ogg"或video/ogg"(我都试过),file"是从文件系统读取的.ogv文件.以下是响应标头:

Where "request" represents the http request, type is either "application/ogg" or "video/ogg" (I've tried both) and "file" is the .ogv file that's been read from the file system. Here are the response headers:

Content-Range   bytes 0-14270463/14270464
Accept-Ranges   bytes
Content-Length   14270464
Connection     keep-alive
Content-Type     video/ogg

我检查了响应头,这段代码似乎工作正常,但有几个问题:

I've examined the response headers and this code appears to be working fine, but there are a couple of problems:

  1. 由于在本地网络上,视频的加载速度似乎很慢.据我所知,使用 firebug 检查响应,文件似乎以大约 150 kb/秒的速度流入.
  2. 视频根本无法播放.即使我等待整个内容加载完毕,HTML 5 视频标签也只会在 Firefox 中显示一个大的x"而不是电影.

有没有人知道我可以做些什么来让视频流通过 node.js 工作?

Does anyone have any ideas as to what I can do to get video streaming working via node.js?

谢谢!
克里斯

推荐答案

在 nodejs 论坛的一些帮助下,我能够让它发挥作用:

I was able to get this to work with some help from the nodejs forums:

http://groups.google.com/group/nodejs/browse_thread/thread/8339e0dc825c057f/822b2dd48f36e890

来自 Google 网上论坛帖子的亮点:

Highlights from the Google Groups thread:

众所周知,谷歌浏览器首先发出一个范围为 0-1024 的请求然后请求范围1024-".

Google chrome is known to first make a request with the range 0-1024 and then request the range "1024-".

response.end(file.slice(start, chunksize), "binary");

response.end(file.slice(start, chunksize), "binary");

那么:

通过设置,我能够让视频在 Firefox 中播放没有问题将连接"标头关闭"

I was able to get the video to play no problems in firefox by setting the "connection" header to "close"

那么:

您似乎错误地计算了内容长度:

Seems that you are incorrectly computing the content-length:

var chunksize = (end-start)+1;

var chunksize = (end-start)+1;

如果 start 是 0,end 是 1,那么在你的情况下,chunksize 是 2,它应该为 1.

If start is 0 and end is 1, in your case chunksize is 2, and it should be 1.

这篇关于通过 node.js 使用 HTML 5 进行视频流传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆