Playing with the code

I finished doing a little freebie side work on a site called The 9-12 Project Show. Well, I wasn’t actually doing work on the site, I was making an alternative site because of a suggestion by Jacob. The site is a page for posting radio and video interviews for 9/12 Candidates; another site I help out with. The site is pretty basic, but the key is the media player used to play back the shows. The original site used the Whimpy Website Audio and Video player. I’m sure it’s a very capable player, but I didn’t like it. At first glance, it didn’t seem like the player could handle playing both video and audio tracks on the same playlist. Being able to play different formats is important because some shows are just radio interviews (call-in), while others are filmed. After doing a quick search, I found LongTail Video and their JW Player. I had never heard of this company before and they probably haven’t been around for very long. However, I did like the initial looks of their player. It supports multiple file types and multiple xml based playlists. It didn’t take me long to realize that this would be the right tool for the job.

After I made a mock-up site using a free template that I hacked down to being useful, I added the player. The owner of The 9-12 Project Show told me that she didn’t want people to have the ability to embed the video on other sites, so that she could possibly get a revenue stream to recoup some of her volunteer efforts. Also, the shows had to stay prominent (or live) for 48 hours. Because of these issues, I had to try and figure out a way to load the video based off of a url parameter. Then we could send the URL to the person interviewed and they could link directly to The 9-12 Project Show and see their video come up in the “live” show.

After messing around with a few scripts that would load the video by number, I started from scratch and found some newer scripts that I modified; here’s what I did and the results.

Resources

First thing was to download the normal version of the JW Player. You have to uncheck the “Include Viral Plugin” box, so that you don’t get the embed or link options inside of the player.

Next you need the latest version of swfobject. This is the script used to load Flash objects.

Offers two optimized Flash Player embed methods; a markup based approach and a method that relies on JavaScript

Finally, you need a playlist for the player. JW Player can use multiple types, but I ended up going with XSPF : XML Shareable Playlist Format. Using the chart and the option “meta” tag, you are able to add all the information you need to get the video information displayed.

Add the JavaScript

I placed all of this JavaScript in the header. The great thing about how this works is, you don’t have to place any JavaScript in the body of the HTML. The script searches for div id’s and inserts the needed code at that point in the page.

Include the swfobject script.

<script type="text/javascript" src="swfobject/swfobject.js"></script>

Code for getting the video title.

Since I need to use links to set the show to play, I need to scrap out the URL parameters. I found this code that easily does the work. It will be called later to get the index of show in the playlist.

	function gup( name )
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
	}

Create the player

The first part of this function makes the link to the playlist random by adding a random number value to the end. The reason for this is to make sure that the latest playlist is loaded and not cached in the browser. There are other options for dynamically passing in the playlist file name, but I am only using one playlist. You can add parameters to customize the look and behavior of the player.

The “mediaspace” name is what the JavaScript will look for in the HTML code to insert the player. You can change this to what ever name you would like, just as long as you have the matching div id in the HTML code.

flashvars

I downloaded one of the free skins available from the LongTail site. The modieus skin had properties very close to the look of the site, therefor it fits in nicely with the overall look. I set the playlist value to show at the bottom of the player.

The player is ready

When the player has been loaded, then the playerReady function inserts the player into the HTML page and then calls the functions to load the player and print out the playlist data.

var player = null;
	var playlist = null;

	function createPlayer() {
		var xxx = encodeURIComponent('media/playlist.xml?t=' + Math.round(1000 * Math.random()));
		var flashvars = {
				file:xxx,
				autostart:"false",
				skin:"mediaplayer/modieus/modieus.swf",
				playlist:"bottom"
		}
		var params = {
				allowfullscreen:"true",
				allowscriptaccess:"always"
		}
		var attributes = {
				id:"player1",
				name:"player1"
		}
		swfobject.embedSWF("mediaplayer/player.swf", "mediaspace", "450", "400", "9.0.115", false, flashvars, params, attributes);
	}

	function playerReady(thePlayer) {
		player = document.getElementById(thePlayer.id);
		addListeners();
		// Get title from url
		var videoitem = gup('video');
		var itemNumber = findPlayListItem(videoitem.replace(/\+/g, ' '));
		// Play play list item based on title selection
		loadNplay(itemNumber);
		printPlaylistData(itemNumber);
	}

Get the playlist index

Before I can get the playlist data or even play the show in the player, I need to know which index the show is in the playlist. Since I wanted to make it easy for someone to link to show and easy for adding more shows to the playlist, I needed to use something else besides the index. I decided to use the shows title value. The title would be passed through the URL like this : ?video=this+is+my+show+title . This function takes the title, which would have the “+” values replaced and find the matching title and index and return that number.

function findPlayListItem(fileTitle) {
		var outItemId = 0;

		playlist = player.getPlaylist();
		if(playlist) {
			var thisTitle = '';
			for(var listItem in playlist) {
				thisTitle = playlist[listItem].title;
				if(thisTitle == fileTitle) {
					outItemId = listItem;
				}
			}
		}
		return outItemId;
	}

Print the playlist data

To make everything seem more dynamic than it is, I need to change the text around the player when a show was loaded. To do this, the JavaScript loads the playlist from the player and puts the values into an Object Array. From there, I determine if the selected value (idx) matches with the playlist and then get the data for that playlist item. The original script was for printing out the entire playlist, but I only need the data for one. The data is put into variables that are assigned to div’s on the HTML page. The innerHTML is replaced with the formatted data.

Custom fields

In the xml playlist, I added a custom tag for a long description of the show.

<meta rel="longdescription"></meta>

I can then call that custom value along with the other data values from the playlist.

playlist[listItem]['longdescription']

In this case, having the long description allows for more information to be shown above the player, while the in player playlist shows a short description (annotation) of the show.

function printPlaylistData(idx) {
		var linkValue = document.getElementById("candidateLink");
		var videoTitle = document.getElementById("candidate");
		var nowPlayingText = document.getElementById("nowplaying");
		var longDescText = document.getElementById("longdescription");

		playlist = player.getPlaylist();
		currentItem = player.index;

		if (playlist) {
			var txt = '';
			for(var listItem in playlist) {
				if(listItem == idx){
					var reverseTitle = playlist[listItem]['title'];
					linkValue.innerHTML = '<p class="links"><a href="' + playlist[listItem]['link'] + '"  title="' + playlist[listItem]['link'] + '" target="_blank">' + playlist[listItem]['link'] + '</a></p>';
					videoTitle.innerHTML = '<p class="credit">' + playlist[listItem]['title'] + '</p>';
					nowPlayingText.innerHTML = '<h2><a href="/?video=' +reverseTitle.replace(/ /g, '+') + '">now playing... ' + playlist[listItem]['title'] + '</a></h2>';
					longDescText.innerHTML = '<p>' + playlist[listItem]['longdescription'] + '</p>';
				}
			}
		} else {
			setTimeout("printPlaylistData()",100);
		}
	}

Add the Listeners

The player allows for listeners, which is basically script waiting for an action to happen and then kicking off other scripts. Since I also needed text to change if the user changed the current show, I needed a listener to pay attention to the ITEM and then reprint the playlist data based on the selection.
The first function adds the listener to the ITEM actions and the second function is the listener action.

function addListeners() {
		if (player) {
			player.addControllerListener("ITEM", "itemListener");
		} else {
			setTimeout("addListeners()",100);
		}
	}

	function itemListener(obj) {
		if (obj.index != currentItem) {
			previousItem = currentItem;
			currentItem = obj.index;
			printPlaylistData(currentItem);
		}
	}

Load the show

The simplest part of the code is loading the file into the player. Since the playlist has all the information, it is just a matter of telling the player which ITEM to start with. And since the other functions determined which index we need from the playlist, it is just a matter of passing in that value.

function loadNplay(idx)
	{
		player.sendEvent('ITEM', idx);
    };

Add the HTML

As I mentioned earlier, the beauty of this code is that you only have to add the JavaScript to the header information. Well, there is the one call to the JavaScript to get everything started, but that’s it.

<body onload="createPlayer();">

The rest of the code is just adding the div tags to the HTML at the places you want things to display.

<div class="post">
	<div class="title">
		<div id="nowplaying">This gets replaced by the show title with a link back to the show</div>
	</div>
	<!--// Current/Selected Candidate Information //-->
	<div class="entry">
		<div id="longdescription">This is where the description appears.</div>
			<div class="meta">
				<div id="candidate">This gets replaced by the show title</div>
				<div id="candidateLink">This gets replaced by the link</div>
			</div>
			<!--// Video Player //-->
			<div id="mediaspace">
				<a href="http://www.macromedia.com/go/getflashplayer">Get flash</a> to see this player.
			</div>
		</div>
</div>

About DeanLogic
Dean has been playing around with programming ever since his family got an IBM PC back in the early 80's. Things have changed since BASICA and Dean has dabbled in HTML, JavaScript, Action Script, Flex, Flash, PHP, C#, C++, J2ME and SQL. On this site Dean likes to share his adventures in coding. And since programming isn't enough of a time killer, Dean has also picked up the hobby of short film creation.

About DeanLogic

Dean has been playing around with programming ever since his family got an IBM PC back in the early 80's. Things have changed since BASICA and Dean has dabbled in HTML, JavaScript, Action Script, Flex, Flash, PHP, C#, C++, J2ME and SQL. On this site Dean likes to share his adventures in coding. And since programming isn't enough of a time killer, Dean has also picked up the hobby of short film creation.