Yesterday, I wrote a simple script to test out the youtube player api.

The demo is meant to test how responsive the API is with multiple videos playing the same time.

Performance

Performance is pretty good, but not perfect (playing about 11 videos). They take a bit to initiate and then subsequently play pretty well. Volume control is also very responsive. Currently, there is a hover binding that mutes all videos except the one being hovered and that works pretty well. Re-sizing videos also works pretty well. Videos are responsive an respond quickly. All that being said, seeking and skipping to other parts of the video is quite slow and not as responsive as everything else. I wasn’t too surprised this would be the slowest part of the demo.

The Code

This particular demo, consists of three components: the video class, a video array that holds these objects, and some jQuery bindings to do stuff with the video. The video class is mainly an abstraction of the Youtube player with a couple of other things, but not really that interesting to look at. What is a bit more interesting is how Youtube handles player and videos, since these things are not necessarily one and the same.

The loading of a video happens in the following order:

1. The player is initiated with SWF object


Video.prototype.init = function(){
	// The video to load.
	$("<div id='c" + this.id + "'></div>").appendTo("#container");
	this.elementId = "video" + this.id;
	// Lets Flash from another domain call JavaScript
	var params = { allowScriptAccess: "always" };
	// The element id of the Flash embed
	var atts = { id: this.elementId, class: "video" };
	// All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
	swfobject.embedSWF("http://www.youtube.com/apiplayer?" +
	"version=3&enablejsapi=1&playerapiid=player" + this.index,
	"c" + this.id, this.w, this.h, "9", null, null, params, atts);
}

2. The Api fires an event that the player is ready.


function onYouTubePlayerReady(playerId) {
     var id = parseInt(playerId.replace("player",""))
     videos[id].createPlayer();
}

3.  A video is cued into the player by its Youtube id.


Video.prototype.createPlayer = function(){
     this.player = document.getElementById(this.elementId);
     this.player.cueVideoById(this.id);
     this.player.setVolume();
     this.playing = false;
}