Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196
News

Create a custom YouTube player

YouTube's javascript player API makes it possible to create a custom player using javascript controls with a chromeless version of its embedded Flash player

Download the full code to accompany this tutorial

A custom skinned YouTube player isn’t possible, right? Well, it is now. Using YouTube’s JavaScript API combined with a chromeless version of its embedded Flash player allows you to control a video window with custom JavaScript/CSS controls. Throw jQuery (http://jquery.com) into the mix and you can create a really nice custom-skinned player with all of the functionality of a basic Flash player.

YouTube’s extensive API also makes it possible to load and play several videos with one player, allowing you to take your player a step further and create a video gallery. A demo player showcasing just about everything you can do with the API is available at http://tinyurl.com/324h6aq. We’ll cover the basic setup of a custom player, as well as how to integrate an optional video gallery. The good folks over at Airwalk (http://airwalk.com) have recently launched a new website showcasing this functionality and have generously allowed us to feature their player, imagery and videos for the purposes of illustration.

01 API reference

When using an API, a good place to start is always the reference. Take a look at the YouTube JavaScript Player API Reference (http://code.google.com/apis/youtube/js_api_reference.html) to get an idea of what’s possible for your player. It’s nice to know this stuff up front so you don’t have to make changes later!

02 Project setup

The code presented in this tutorial is all XHTML 1.0 Transitional. So really, the only requirement here is that you use that for your doctype. Beyond that you could keep things organised by storing assets (css, images, JavaScript) in a data folder, separated in subfolders by type.

03 Some simple CSS
The XHTML/CSS setup on the CD is pretty easy. The CSS contains two sections, one for some generic reset declarations to strip the browser defaults off of most items and another section for the player layout.

@charset “utf-8”;
/******************************
* Reset *
* *
******************************
/ */
* {
padding:0;
margin:0;
border:none;
}
html {
height:100%; width:100%;
}
body {
font:16px/24px Arial, Helvetica, sans-serif;
height:100%; width:100%; background:#fff
url(../images/body-bg.gif) top left repeat;
}
/******************************
* Layout *
* *
******************************
/ */
/* ... */

04 Play/pause button setup

The play/pause button should be set up with a sprite background image containing both the ‘playing’ and ‘paused’ states. This way, when the state changes you can simply move the background image and there is no need to load a new image into the button. We’ll cover how the switch works later in the tutorial.

05 Seekbar setup

The seekbar should be set up with a sprite background. The functionality will be different as the background will be positioned to reflect the percentage of the video that’s played. Set the background colour of the seekbar to any colour, then add a background image of a different colour that’s large enough to fill the seekbar.

06 Mute button setup

The mute/unmute button should be set up exactly like the play/pause button. We’ll cover how to switch the position later in the tutorial.

07 JavaScript framework

For JavaScript, include a couple frameworks and your own player.js file. The first framework, jQuery (http://jquery.com), will be used to reference the controls, bind event listeners to them and update their display as the player state changes. Next, SWFObject (http://code. google.com/p/swfobject/) will be used to embed the chromeless Flash player on the page. Finally, your own player.js file will tie it all together unobtrusively (no in line JavaScript will be used). Let’s look closer at player.js…

08 Document ready
The first thing you need to do in player.js is set a few global variables for the player and listen for the DOM to be ready. As you can see, jQuery makes this really easy by simply attaching a ready listener to the document object. Inside this listener, now that items are ready, attach the listeners to the player controls.

var player = null;
var ready = false;
var seekReady = false;
var playheadInterval = 0;
var tooltip = null;
$(document).ready(function() {
// embed chromless player
var id = ‘flash’;
var src = ‘pgfLv6-Qv0w’;
var params = {allowScriptAccess:”always”};

09 YouTube player ready
The function “onYouTubePlayerReady” is required to be a global object by the YouTube Chromeless Flash Player,
and will be called when the player is ready to accept commands. In this function, get a reference to the player, add a state change event listener and flip the ready flag.

/************************************************
* onYouTubePlayerReady:void *
* *
* Called from the YouTube player API. *
* This player is ready for action! *
************************************************
/ */
onYouTubePlayerReady = function() {
player = document.getElementById(‘myplayer’);
player.addEventListener(“onStateChange”,
“onPlayerStateChange”);
ready = true;
}

10 YouTube player state
Each time the YouTube player’s state changes, it’ll dispatch a state change event and call this function. The new player state code will be passed into this function. You can see which state is mapped to which code by looking at the comments in the code below.

/************************************************
* onPlayerStateChange:void *
* *
* Handle player state change. *
************************************************
/ */
onPlayerStateChange = function(s) {
switch(s) {
case -1: // unstarted
return;
case 0: // ended
resetPlayer();
return;
case 1: // playing

11 Update the playhead
While the player is playing, the “updatePlayhead” function should be called on an interval every ten milliseconds. This function takes the player’s playhead time divided by the player’s total time to determine the percentage of the video that has been played, and sets the position of the background sprite of the seekbar respectively. A portion of the code for this step is shown here for reference.

/************************************************
* updatePlayhead:void *
* *
* Update the seekbar. *
************************************************
/ */
updatePlayhead = function() {
if(typeof(player.getCurrentTime) ==
‘undefined’) {
clearInterval(playheadInterval);
return;

12 Play/pause
The “playPause” function should check the player’s state, play the video if it is unstarted, ended, or paused and pause the video if it is playing. This function also manages the display of the play/pause button by setting the position of the background image depending on the player state.

/************************************************
* playPause:void *
* *
* Toggle play/pause. *
************************************************
/ */
playPause = function() {
switch(player.getPlayerState()) {
case -1: // unstarted
case 0: // ended
case 2: // paused
player.playVideo();

13 Seek percentage
The seekbar should also handle clicks to seek the video.  This is done by determining the x position where the user clicked on the seekbar and dividing that by the total width of the seekbar. This gives us a percentage to seek the video to.

/************************************************
* seekToPercent:void *
* *
* Seek to the passed percentage. *
* *
* percent:Number - percent to seek to. *
************************************************
/ */
seekToPercent = function(percent) {
var time = percent * player.getDuration();
player.seekTo(time, true);
}

14 Toggle sound
The “toggleSound” function should check if the player is currently muted and unmute it, and vice versa. This function also manages the display of the mute/unmute button by setting the position of the background image depending on the player’s sound state.

/************************************************
* toggleSound:void *
* *
* Toggle mute/unmute. *
************************************************
/ */
toggleSound = function() {
if(player.isMuted()) {
player.unMute();
$(‘#mute-btn’).css(‘backgroundposition’,
‘0px 0px’);
} else {
player.mute();
$(‘#mute-btn’).css(‘background

15 Final steps to finish

That’s it! You should have a functioning custom player with play/pause, seek and mute functionality. If you have any problems, reference the files included on the CD. If you would like to take your player a step further, check out the ‘In Detail’ section in this article which covers turning your player into a gallery.

FURTHER TECHNIQUE

Turn your custom player into a gallery

In the example code there are several pieces of code denoted with the comment “Video Gallery
(Optional).” These optional blocks are what is required to add the video gallery.

Step 1: Thumbnail list XHTML/CSS
The first step is to create an unordered list (or any other element that you prefer) to contain the links to each video in
your gallery. The example on the CD shows a list floated next to the player with square thumbnails floated in three  columns. Each list item contains a link with a call to the “loadVideo” function and passes the video id. This is really the only requirement, everything else can be styled as you choose.

Step 2: Adding a preview tooltip
Next, add a preview tooltip to give the user a preview of each video before they click to load it. In the example on the CD you will find a section commented “tooltip” in the document ready handler (player.js line 44). In this section, a new tooltip div is created and styled. Then listeners are added to each thumbnail in our unordered list to fill, position and show the tooltip on mouseenter and hide the tooltip on mouseleave.

Step 3: The “loadVideo” function
In the “loadVideo” function flip the ready flag back false and use the YouTube JavaScript API’s “cueVideoById” function to load a new video. Note that the “cueVideoById” function also takes parameters for start time and quality which have been set to “0” and “default” for the purposes of this example. When the new video is loaded, the player will dispatch the “stateChange” event with a “cued” status. Simply handle this event in the “onPlayerStateChanged” listener and reset the
player/controls for the new video.

×