Skip to content

Instantly share code, notes, and snippets.

@shamansir
Created February 10, 2015 09:47
Show Gist options
  • Select an option

  • Save shamansir/f74ae2303f069cbcd1e8 to your computer and use it in GitHub Desktop.

Select an option

Save shamansir/f74ae2303f069cbcd1e8 to your computer and use it in GitHub Desktop.
monitor html5 audio loading progress
// source: http://jspro.brothercake.com/media-events/progress.html
// article: http://www.sitepoint.com/essential-audio-and-video-events-for-html5/
(function()
{
//create a new video element with "auto" preload and native "controls"
var media = document.body.appendChild(document.createElement('video'));
media.setAttribute('preload', 'auto');
media.setAttribute('controls', 'controls');
//create the progress-meter element
var progress = document.body.appendChild(document.createElement('div'));
progress.id = 'progress';
//define a progress abstraction
function onprogress()
{
//get the buffered ranges data
var ranges = [];
for(var i = 0; i < media.buffered.length; i ++)
{
ranges.push([
media.buffered.start(i),
media.buffered.end(i)
]);
}
//get the current collection of spans inside the container
var spans = progress.getElementsByTagName('span');
//then add or remove spans so we have the same number as time ranges
while(spans.length < media.buffered.length)
{
progress.appendChild(document.createElement('span'));
}
while(spans.length > media.buffered.length)
{
progress.removeChild(progress.lastChild);
}
//now iterate through the ranges and convert each set of timings
//to a percentage position and width for the corresponding span
for(var i = 0; i < media.buffered.length; i ++)
{
spans[i].style.left = Math.round
(
(100 / media.duration) //the width of 1s
*
ranges[i][0]
)
+ '%';
spans[i].style.width = Math.round
(
(100 / media.duration) //the width of 1s
*
(ranges[i][1] - ranges[i][0])
)
+ '%';
}
}
//bind progress and loadedmetadata events to call the progress abstraction
media.addEventListener('progress', onprogress, false);
media.addEventListener('loadedmetadata', onprogress, false);
//finally set the SRC according to supported type, including a timestamp query
//for testing purposes, so that reloading the page is as though it were never cached
for(var types = ['mp4','webm'], i = 0; i < types.length; i ++)
{
if(/(maybe|probably)/.test(media.canPlayType('video/' + types[i])))
{
media.type = 'video/' + types[i];
media.src = 'http://jspro.brothercake.com/media-events/media/'
+ 'BadgerWatch.' + types[i]
+ '?nocache='+ new Date().getTime();
break;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment