HomeEmbed [SimpleCustom Playlist ]  CreateAPIProject Page @SourceForge

How To Embed The Playlist In Your Web Page With Just The playlist.js

This document covers the v0.4.3 release of the YouTube Playlist Player, and is intended to complement the API reference documentation. If you have questions or comments, you can e-mail the author, Matt Albrecht (groboclown@gmail.com) .

Future Version Warning: with the 1.0 release, the naming convention will change, and the URL for the Javascript file will change.

Preparing Your Web Page

To embed the playlist, you must first prepare it for embedding the chrome-free YouTube Flash player. Start by adding a <div> in the body of your page, marked with a unique ID, so that the embedding tools can find the right place to insert the player:

        <div id="ytapiplayer" name="ytapiplayer">
            <a href="http://www.adobe.com/go/getflashplayer">Get
            flash</a> to see this player, or enable Flash + JavaScript,
            if your browser has them disabled.
        </div></pre>

Next, you will need to include the correct JavaScript files in the <head> section of your page. Here, we use the swfobject.js to help with the loading of the Flash player.

<html>
  <head>
    <script
      src="http://swfobject.googlecode.com/svn/tags/rc3/swfobject/src/swfobject.js"
      type="text/javascript"></script>
    <script
      src="http://ytsnip.sf.net/playlist.js"
      type="text/javascript"></script>

Loading The Player

The YouTube player needs to be configured and invoked in JavaScript once the page has loaded. This means that we need a function to load our player, and an onload attribute on the <body> of the page. Note that the id of the player div tag must match the id in the embedSWF call (here, it's "ytapiplayer"). The "myytplayer" is the ID to be set in the created YouTube player.

<html>
    <head>
        ...
        <script type="text/javascript">
function createPlayer() {
    var params = { allowScriptAccess: "always", userAgentButton: "x" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF(
      "http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer", 
      "ytapiplayer", "425", "356", "8", null, null, params, atts);
}
        </script>
    </head>
    <body onload="createPlayer()">

You can learn more about this at the YouTube developer reference page.

Responding To Player Events

Embedding the player is half the problem. When the Flash player finishes loading, it executes a no-argument function on the page named onYouTubePlayerReady, which allows the page to start interacting with the player. The player, during its operation, also generates two kinds of events, so we'll register some listeners with the player while we're here. These functions should be added to the <head> section.

var ytplayer = null;
function onYouTubePlayerReady() {
    ytplayer = document.getElementById("myytplayer");
    addListeners();
}

function addListeners() {
    if (ytplayer) {
        ytplayer.addEventListener("onError", "myOnErrorListener");
        ytplayer.addEventListener("onStateChange", "myOnStateListener");
    } else {
        // try again until the player is properly loaded
        setTimeout("addListeners()",100);
    }
}

We'll get to the event listeners in a bit. You'll notice that the addListeners() method will continue to retry adding the listeners until the player is correctly loaded.

JavaScript Preparation For The Playlist

We now have the infrastructure in place to start adding the Playlist. The Playlist class requires your web page to correctly register the playlist with the YouTube player events, and with an interval timer (to capture when a video should end). We'll start by augmenting the addListeners() method above.

var playlist = null;
function addListeners() {
    if (ytplayer) {
        ytplayer.addEventListener("onError", "myOnErrorListener");
        ytplayer.addEventListener("onStateChange", "myOnStateListener");
        
        playlist = new PlaylistObject(ytplayer);
        
        // add our videos to the playlist
        playlist.addAll(videoList);
        
        // tell the playlist to initialize the YouTube player with the
        // videos we just added
        playlist.ready();
        
        // continuous timer thread - millisecond times
        setInterval("myTimer()", 250);
    } else {
        // try again until the player is properly loaded
        setTimeout("addListeners()",100);
    }
}
function myOnErrorListener(err) {
    // Trivial error reporting.  Your page should so something smarter.
    if (err == 100) {
        alert("The video is not available.");
    } else
    if (err == 101) {
        alert("The video cannot be embedded.");
    } else {
        alert("Unexpected error: "+err);
    }
}
function myOnStateListener(state) {
    playlist.onStateChange(state);
}
function myTimer() {
    playlist.onTimer();
}

I deliberately prefixed many of these functions with "my" to indicate where it's appropriate (and expected) to add code to enhance the behavior of your web page. For example, the myTimer() is the place you want to give feedback to the user describing the state of the YouTube player.

Adding Videos To The Playlist

The above snippet of code includes a reference to a undefined videoList object. This should be created before executing this line of code.

The playlist method addAll takes an array of objects that describe the different videos to play. Alternatively, you can add them one at a time with the add method. This playlist is usually constructed something like this:

var videoList = new Array(
  { vId: "k1UgOxBytc" }, { vId: "ZM85Ola_FCY" } );

You can put as many values into this object as you please, but there are three reserved keys:

KeyValue TypeDescription
vIdstring YouTube video ID of the video to show
startfloat offset (in seconds) from the start of the video, for where the video should begin playing. If not specified, this defaults to 0.
endfloat offset (in seconds) from the start of the video, for where the video should stop playing. Any value less than the start value means the video will play to the end. If not specified, this defaults to -1.

Adding Controls

You now have a YouTube player that can play a series of video clips! However, since this is the chrome-free player, your users have no way to control the video, even for something as simple as muting the volume.

You will need to implement these controls yourself in JavaScript. The YouTube JavaScript API documentation can help you with discovering what is possible.

Responding To Playlist Events

Following up with the section on Responding to Player Events, the playlist itself generates events that should be listened for proper response to errors and video updates.

To listen to events, set the callback field of the playlist object to your callback function:

function addListeners() {
    if (ytplayer) {
        ...
        
        playlist = new PlaylistObject(ytplayer);
        playlist.callback = myPlaylistCallback;
        
        ...
    }
}
function myPlaylistCallback(obj) {
    if (obj.status == Playlist_ERROR) {
        var vid = obj.playlist.getCurrentVideo();
        if (vid) {
            alert("There was an error playing video " +
                vid.vId + ": " + obj.msg);
        } else {
            alert("There was a playlist error: " + obj.msg);
        }
    } else
    if (obj.status == Playlist_NEXT) {
        alert("Playlist now playing " + obj.video.vId);
    } else
    if (obj.status == Playlist_FINISHED) {
        alert("Playlist finished");
    }
}

For a complete list of the data stored in the obj parameter to the callback function, please reference the API reference documentation.