jQuery: create an HTML5 media compilation (audio and video)

HTML5 audio and video elements are surely a great feature to explore especially when we start studying carefully their powerful APIs. In this article we'll see how to create an HTML5 media compilation with jQuery.

Each video or audio element has a native event called ended. This event triggers when a media element stops playing, that is, when it reaches the end of its total duration.

Knowing this, we can use an array containing several media sources and an incremental index to move to the next media and play it:


(function($) {
    
    $.preloadCompilation = function(type, files) {
    	var len = files.length,
    	    i;
    	for(i = 0; i < len; i++) {
    		var element = document.createElement(type);
    		var src = files[i];
    		element.src = src;
    	}
    };
	
	$.fn.compilation = function(options) {
		var settings = {
			files: [],
			media: '#video'
		};
		options = $.extend(settings, options);
		
		var mediaIndex = -1;
		
		var play = function(media) {
			mediaIndex++;
			if(mediaIndex == options.files.length) {
				mediaIndex = 0;
			}
			media.src = options.files[mediaIndex];
			media.play();
		};
		
		return this.each(function() {
			var $element = $(this);
			var media = $(options.media, $element)[0];
			play(media);
			$(media).on('ended', function() {
				play(media);
			});
		});
	};
	
})(jQuery);

Here's an example which makes use of Deferred Objects to properly preload videos (you can always display a loading message when the preloading function is executing):


$(function() {
  var files = ['Banded_Lapwing.ogg', 'Cotton_Pygmy-Goose.ogg', 'White-browed_Treecreeper.ogg'];
  
  $.when($.preloadCompilation('video', files)).done(function() { 
	$('#playlist').compilation({
		files: files
	});
  });
  
});

[view-example url="http://codepen.io/gabrieleromanato/pen/azevH"]
Back to top