Dynamically embed looping clips from YouTube

Recently I needed to come up with a way to play short looping video clips on a web site, without the distraction of controls, and muted to prevent them from being annoying. (Similar in a sense to the direction Imgur is taking in replacing the GIF with control-less videos).

A lot is possible with the YouTube Player Tools. You can get most of the way just with query parameters, including disabling the controls and setting a start and end timestamp.

However, I encountered multiple roadblocks trying to get this to work properly, and it ended up being Javascript-dependent. The embedSWF function from SWFObject makes embedding fairly easy, but the callback functions take some finesse.

Here are some issues that need to be worked around:

Here is the callback function I came up with to handle all of this:

function youTubeClipCallback(event) {
    var player = event.ref,
        callbackName = '_youtubeCallback_' + event.id;
    if(!player.playVideo) {
        setTimeout(function() { youTubeClipCallback(event); }, 10);
        return;
    }
    player.mute();
    player.playVideo();
    player.addEventListener('onStateChange', callbackName);
    window[callbackName] = function(state) {
        if(state === 0) {  // 0 is stopped
            player.playVideo();
        }
    }
}

This function sets up a simple polling timer to make sure the API has initialized before using it (in this case, muting and then auto-playing the video).

The onStateChange handler is then given a unique (global) name by being inserted into the window object.

After all this there are still some annoyances:

Apart from that, the method works. The clips autoplay and loop, and with controls active you can observe that no more of the video is buffered than necessary.