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);
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:
- The video appears to load very slowly for being on a local network. From what I can tell examining the response using firebug, the file appears to be streamed in at about 150 kb/sec.
- The video doesn't play at all. Even if I wait for the whole thing to load, the HTML 5 video tag just shows a big "x" instead of a movie in firefox.
Does anyone have any ideas as to what I can do to get video streaming working via node.js?
Thanks!
Chris
Based on Sam9291's answer, I rewrote the function using
createReadStream()
and fixing some problems:I am using the MVC framework sails.js on top of Node.js and I managed to get it working fine with the following code:
Hope this helps
I found this solution which seems to be simpler and (unlike the checked answer) works for me. (I tried adapting the coffeescript solution at the end of that thread and it kind of worked once I dealt with the fact that the initial request (for "bytes=0-") blows it up.
http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
My actual implementation:
I know this is a really old question, but as Google seems to like it I thought it would be worth pointing out that I wrote a Node.js video streaming module (Github, or via NPM) that's hopefully worth a look too.
This solution does an asynchronous read of a server side video or audio media file ... it spins up a nodejs server at URL visible at
http://localhost:8888/
also it correctly handles client side HTML5 (browser/app) forward/back UI widget slider movements
save below code snippet as server side file :
... execute it on server side using
enjoy
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
Highlights from the Google Groups thread:
Then:
Then: