Multimedia on the Web: JW FLV Player JavaScript API Tutorial

If you’re creating a new media site, you will need a multimedia player rather sooner than later. There are many options available, the easiest is embedding something that already exists. For instance, if you want to put a movie on your site, you could go for a YouTube embedded player. If you want more options, even interactivity, you need something more flexible. You could do much worse than picking the JW FLV Player.

Before you read on, go ahead and open the example to take a look at what we will create.

The player is actually a Flash applet that you can embed in your page. The neat thing, is that it can be completely controlled from JavaScript. There’s a bunch of information on the website, but it’s not very clear how it all ties together.

First, you need to initialize the player:

var so = new SWFObject('jwflvplayer/player-viral.swf','mpl','300','300','9');
so.addParam('allowscriptaccess','always');
so.addParam('allowfullscreen','true');
so.write('player');

This will put a 300×300 sized player in the div-element with id “player”. It won’t load any songs yet. This we will do in a later step. When the player is done loading, it will call the “playerReady” method.

function playerReady(obj) {
    player = document.getElementById(obj.id);
    player.addControllerListener("PLAYLIST", "playlistLoaded");
    player.addModelListener("ERROR", "error");
    player.addModelListener("STATE", "stateChanged");
};

In this method, we initialize a few listeners. One is listening to playlist events (fired when new songs are loaded), another will display error messages and the third is used as an example how to display the state of the player. The JW Player wiki has a full list of all events.

Most of those methods themselves are plain JavaScript, so they are not that interesting, but you can take a look in the source of the example.

The final step to get the player to actually load up a song. It’s as easy as sending a “play” event:

player.sendEvent("LOAD", "music/"+event.target.innerHTML);

For all the details, take a closer look at the example.

There are many things still missing, but this should get you started. For instance, the player will only play one song at a time and the viral code is not functional (the embedding). But those will be discusses in further posts. And if you have any questions, feel free to leave them in the comments.