Skip to content

Instantly share code, notes, and snippets.

@hengkiardo
Created February 21, 2014 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hengkiardo/9129379 to your computer and use it in GitHub Desktop.
Save hengkiardo/9129379 to your computer and use it in GitHub Desktop.
How to prefetch video/audio files for uninterrupted playback in HTML5 video/audio
function e(id) {
return document.getElementById(id);
}
function loaded(blob_uri) {
// Clear progress indicator.
var container = e("container");
container.innerHTML = "";
var v = document.createElement("video");
v.src = blob_uri;
v.autoplay = true;
v.volume = 0.4;
v.controls = true;
container.appendChild(v);
}
function error(pc) {
e("container").innerHTML = "Error prefetching video";
}
function progress(pc) {
e("container").innerHTML = "Prefetching video... " + pc + "%";
}
function prefetch_file(url,
fetched_callback,
progress_callback,
error_callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
var URL = window.URL || window.webkitURL;
var blob_url = URL.createObjectURL(xhr.response);
fetched_callback(blob_url);
} else {
error_callback();
}
}, false);
var prev_pc = 0;
xhr.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var pc = Math.round((event.loaded / event.total) * 100);
if (pc != prev_pc) {
prev_pc = pc;
progress_callback(pc);
}
}
});
xhr.send();
}
var resource = document.createElement("video").canPlayType("video/mp4")
? "bruce_vs_ironman.mp4" : "bruce_vs_ironman.webm";
prefetch_file(resource, loaded, progress, error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment