Dynamically Loading a Player Using JavaScript

In this topic you will learn how to dynamically add or remove players from a page using the createExperiences() and unload() methods in the Video Cloud JavaScript Player API.

The steps outlined in this topic are for Flash based players and will not work in HTML5 players and may prevent HTML5 players from functioning.

When you use the standard Video Cloud JavaScript embed code, the player is rendered along with the rest of the page as it loads. If you prefer to load the player after that, perhaps when the user clicks on a button (as in an AJAX interface), you can dynamically create the player using the createExperiences() method in the standard Video Cloud JavaScript that is included with the player JavaScript publishing code. Conversely, if you want to remove a player from the page you can do so with the unload() method of the Experience Module in the Flash-only Player API. This article is meant to describe how to work with these two methods so you can add and remove Video Cloud players from the page as necessary. There is a working sample below:

Choose a video

Place holder for player. id="placeHolder"

Instead of placing the JavaScript player publishing code provided by the Video Cloud Publishing module directly in the page where the player is to be rendered, we will be creating this code on the fly. The following code will be responsible for generating an object tag for the player, along with the param tags within that tag that will control all of the attributes of the player we are going to be loading. After that, we will use the createExperiences() method to instantiate the new player object and decide where it is to be rendered by providing the id of an HTML element in the page for it to be attached.

Creating the Player

To begin, you'll want to ensure that the player you are working with has the ActionScript/JavaScript Player APIs enabled in the Player Settings. You also need to include the BrightcoveExperiences.js file and JavaScript version of the Flash-only Player API. This should be done using script tags like this:

<script language="JavaScript" type="text/javascript" 
        src="http://admin.brightcove.com/js/BrightcoveExperiences.js">
</script>
<script language="JavaScript" type="text/javascript" 
        src="http://admin.brightcove.com/js/APIModules_all.js">
</script>

This will give you access to the JavaScript methods we will use to create and, if necessary, remove the player. Note that if you do not need to remove the player, then the Flash-only Player API is not required.

Next you will need to know where you want the player to be rendered. In this example, I will use a div tag with its id set to "placeHolder":

<div id="placeHolder" style="background-color:#64AAB2;width:485px;height:270px;text-align: center;padding:5px;">

To create the player, I'm going to need some type of event that can call a function. For this example, I'm going to use a simple HTML button.

<button onclick="BCL.addPlayer()" />Add Player</button>

When clicked, this button will execute the BCL.addPlayer() function. This function works with the template for the player object code, inserting player-specific parameter values into it. I've separated out those parameters from the rest of the code to make it easy for you to see what you would need to replace, and also to show how you could provide the viewer with a choice of several players if you wished to. The player data and template are defined outside of the function, which then uses a simple templating function (BCL.markup()) to insert the data into the template. The code is then inserted into the placeholder div, and the brightcove.createExperiences() function called to instantiate the player:

// namespace to keep the global clear of clutter
var BCL = {};
// data for our player -- note that it must have ActionScript/JavaScript APIs enabled!!
BCL.playerData = { "playerID" : "1464964203001",
                    "playerKey" : "AQ~~,AAAADXdqFgE~,aEKmio9UXajW-cv0zfxA9HrUvcL8ic54",
                    "width" : "480",
                    "height" : "270",
                    "videoID" : "734462565001" };
// flag to keep track of whether there is a player
BCL.isPlayerAdded = false;
// template for the player object - will populate it with data using markup()
BCL.playerTemplate = "<div style=\"display:none\"></div><object id=\"myExperience\" class=\"BrightcoveExperience\"><param name=\"bgcolor\" value=\"#64AAB2\" /><param name=\"width\" value=\"{{width}}\" /><param name=\"height\" value=\"{{height}}\" /><param name=\"playerID\" value=\"{{playerID}}\" /><param name=\"playerKey\" value=\"{{playerKey}}\" /><param name=\"isVid\" value=\"true\" /><param name=\"isUI\" value=\"true\" /><param name=\"dynamicStreaming\" value=\"true\" /><param name=\"@videoPlayer\" value=\"{{videoID}}\"; /><param name=\"templateLoadHandler\" value=\"BCL.onTemplateLoaded\"</object>";
BCL.addPlayer = function () {
  // if we don't already have a player
  if (BCL.isPlayerAdded == false) {
    BCL.isPlayerAdded = true;
    var playerHTML = "";
    // set the videoID to the selected video
    BCL.playerData.videoID = BCL.videoData[BCL.videoSelect.selectedIndex].videoID;
    // populate the player object template
    playerHTML = BCL.markup(BCL.playerTemplate, BCL.playerData);
    // inject the player code into the DOM
    document.getElementById("placeHolder").innerHTML = playerHTML;
    // instantiate the player
    brightcove.createExperiences();
  }
  // user must have requested a different video for player already loaded
  else {
    console.log(BCL.videoSelect.selectedIndex);
    BCL.videoPlayer.loadVideo(BCL.videoData[BCL.videoSelect.selectedIndex].videoID);
  }
};
/* 
simple HTML templating function
 array example:
   demo.markup("<div>{{1}}, {{0}}</div>", ["John", "Doe"]);
 object example:
   demo.markup("<div>{{last}}, {{first}}</div>", {first:"John", last:"Doe"});
*/
BCL.markup = function (html, data) {
    var m;
    var i = 0;
    var match = html.match(data instanceof Array ? /{{\d+}}/g : /{{\w+}}/g) || [];

    while (m = match[i++]) {
        html = html.replace(m, data[m.substr(2, m.length-4)]);
    }
    return html;
};

You will notice the extra else statement in the BCL.addPlayer() function. I'll explain that soon.

Removing the Player

First, let's look at how we remove the player. For this we need the Flash-only Player API. so I included a param in the player template code to specify the templateLoadHandler as BCL.onTemplateLoaded(). In this function, I get references to the Experience and Video Player Modules:

// player template loaded handler
BCL.onTemplateLoaded = function (id) {
  // get a reference to the player
  BCL.player = brightcove.getExperience(id);
  // get references to the experience and video player modules
  BCL.experienceModule = BCL.player.getModule(APIModules.EXPERIENCE);
  BCL.videoPlayer = BCL.player.getModule(APIModules.VIDEO_PLAYER);
};

The BCL.removePlayer() function itself simply calls the Experience Module unload() method and removes the player code from the DOM:

// function to remove the player
BCL.removePlayer = function () {
  // do this only if we have a player
  if(BCL.isPlayerAdded == true) {
    BCL.isPlayerAdded = false;
    // unload the player
    BCL.experienceModule.unload();
    // remove the player code
    document.getElementById("placeHolder").innerHTML = "";
  }
};

Loading Different Videos

The rest of the code is a simply provides a choice of videos to the viewer by embedding some video data in the script and then loading it into a select control when the page loads:

// video data - optional - if you want to give the viewer choices
BCL.videoData = [{ "videoID" : "734462565001",
                   "displayName" : "Tigers" },
                 { "videoID" : "734451479001",
                   "displayName" : "Lion Fish" },
                 { "videoID" : "1194921694001",
                   "displayName" : "Dolphins" }];
// function to generate the video select control, called on page load
window.onload = function () {
  var selectorHTML = "<select id="\"videoSelect\"" onchange="\"BCL.addPlayer();\"">";   var optionTemplate = "<option>{{displayName}}";      for (var i = 0; i < BCL.videoData.length; i++) {     selectorHTML += BCL.markup(optionTemplate, BCL.videoData[i]);   };                      selectorHTML += "</select>";
  document.getElementById("videoSelector").innerHTML += selectorHTML;
  // save a reference to the select control
  BCL.videoSelect = document.getElementById("videoSelect");
}

As you can see, change events in the select control call the BCL.addPlayer() function. So if there is no player, this loads one, using the id the selected video. If there already is a player, the loadVideo() method of the Video Player Module loads the selected video.

Post new comment

The content of this field is kept private and will not be shown publicly.
0

Comments