Skip to content

Instantly share code, notes, and snippets.

@btotr
Last active March 23, 2021 05:34
Show Gist options
  • Save btotr/9249810 to your computer and use it in GitHub Desktop.
Save btotr/9249810 to your computer and use it in GitHub Desktop.
media source with range
<html>
<head>
<title>ms test</title>
</head>
<body>
<video autoplay></video>
<script>
var video = document.getElementsByTagName("video")[0],
start = 0,
length = 15477531,
chunks = 1,
file = 'http://localhost:8888/video',
mediaSource = new MediaSource,
chunkSize = Math.ceil(length/chunks);
mediaSource.addEventListener('sourceopen', function() {
console.log("d")
var sb = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.640028"');
sb.addEventListener('updateend', function() {
if (i == chunks - 1) {
//mediaSource.endOfStream();
return;
}
loadChunk(++i)
}, false);
loadChunk(0);
});
mediaSource.addEventListener('sourceclose', function() {
console.log("ended")
});
video.src = window.URL.createObjectURL(mediaSource);
var i = 0;
function loadChunk(i){
var xhr = new XMLHttpRequest()
xhr.open("GET", file, true);
xhr.responseType = 'arraybuffer';
var startByte = parseInt(start + chunkSize*i);
xhr.setRequestHeader('Range', 'bytes=' + start + chunkSize*i + '-' + (start + chunkSize - 1));
xhr.addEventListener('load', function(e) {
mediaSource.sourceBuffers[0].appendBuffer(new Uint8Array(xhr.response));
});
xhr.send();
}
</script>
</body>
</html>
var fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
var indexPage, movie;
// load the video files and the index html page
fs.readFile(path.resolve(__dirname,"media/test-video-1MB.mp4"), function (err, data) {
if (err) {
throw err;
}
movie = data;
});
fs.readFile(path.resolve(__dirname,"index.html"), function (err, data) {
if (err) {
throw err;
}
indexPage = data;
});
// create http server
http.createServer(function (req, res) {
var reqResource = url.parse(req.url).pathname;
//console.log("Resource: " + reqResource);
if(reqResource == "/"){
//console.log(req.headers)
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(indexPage);
res.end();
} else if (reqResource == "/favicon.ico"){
res.writeHead(404);
res.end();
} else {
var total;
if(reqResource == "/video"){
total = movie.length;
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;
res.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type":"video/mp4"});
res.end(movie.slice(start, end+1), "binary");
}
}
}).listen(8888);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment