HomeEmbed [SimpleCustom Playlist ]  CreateAPIProject Page @SourceForge

How To Embed The Playlist In Your Web Page

This document covers the v0.5.0 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.

<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>
    <script
      src="http://ytsnip.sf.net/playlist-helper.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 createPlayer call (here, it's "ytapiplayer").

<html>
    <head>
        ...
        <script type="text/javascript">
function initPage() {
    var playObj =  PlaylistHelper.createPlayer("ytapiplayer");
}
        </script>
    </head>
    <body onload="initPage()">

This function call will do a lot of things behind the scenes, including creating a timer thread, and reacting to all the YouTube player events. You won't need to worry about any of this, as the PlaylistHelper handles this for you. If you are looking for details, you can read over the embedding guide with just playlist.js.

This code can be seen in action in this page.

Adding Videos To The Playlist

The above snippet of code will create our player, but we won't have any videos available for the playlist. You should see a YouTube player widget with a black screen and no controls. Not very interesting.

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

var videoList = new Array(
  { vId: "ZM85Ola_FCY" }, { vId: "CnB-9ZTajS8" } );

You can put as many values into this object as you please, but there are six 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.
qualitystring quality of the video to display. You can specify "hq" or "hd" for high-quality or high-definition (respectively).

The other two keywords are width and height. These are described later.

In order to have our example play these videos upon loading the page, we'll need to create the player in a different way, which will allow us to initialize it.

var videoList = new Array(
    {
            title:"BMW X3 TV commercial",
            vId:"ZM85Ola_FCY",
            url:"http://www.youtube.com/watch?v=ZM85Ola_FCY", //optional
            start: 0.0,
            end: 15.0
    },
    {
            title:"BMW 3-Series 2007",
            vId:"CnB-9ZTajS8",
            start: 4.2,
            end: 10
    });
function initPage() {
    var playObj =  PlaylistHelper.addPlayer("ytapiplayer");
    playObj.addVideos(videoList);
    playObj.autostart = true;
    PlaylistHelper.createPlayers();
}

By calling PlaylistHelper.addPlayer first, we have a chance to set the initial playlist and some other parameters before we tell the helper to actually embed the player with the call PlaylistHelper.createPlayers().

Our advancing web page has developed into this.

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. The player object itself is in the playObj.player value.

Simple controls for these aren't difficult, though. Here's some examples of the common player functions:

function play() {
    if (playObj) playObj.play();
}
function pause() {
    if (playObj) playObj.pause();
}
function nextVid() {
    if (playObj) playObj.nextVideo(true);
}
function prevVid() {
    if (playObj) playObj.prevVideo(true);
}

For these, we had to put the playObj into a page-wide global variable. You'll also notice some protection to keep the buttons from causing errors if the player hasn't been initialized yet. The ever-growing sample web-page can be found here.

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 playObj object to your callback function:

var playObj = null;
function initPage() {
    playObj =  PlaylistHelper.addPlayer("ytapiplayer");
    playObj.addVideos(videoList);
    playObj.autostart = true;
    playObj.callback = myPlaylistCallback;
    PlaylistHelper.createPlayers();
}
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");
    }
}

Along with this, the PlaylistHelper may encounter problems. To counter this, you should register a simple error handler:

function initPage() {
    PlaylistHelper.userErrorCallback = errorCallback;
    ...
}
function errorCallback(msg) {
    document.getElementById("errordiv").innerHTML = "Error: "+msg;
}

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

Our example has now developed into this. With some clean-up, it could become a usable page.

Resizing The Player

At any time, you can resize the player in the web page by running the following code, obviously replacing newWidth and newHeight with the appropriate values:

playObj.player.width = newWidth;
playObj.player.height = newHeight;

Also, the playlist allows for auto-sizing the player depending on the video. During initialization of the playObj, you can set playObj.autoResize = true. Or, after the playlist has been created, you can call playObj.playlist.autoResize = true. This allows for any video object which as set width and height to change the player's dimensions.