Use Web Standards With Flash

I find that my Flash work of late has been on smaller things — individual components that fit into larger XHTML/CSS sites rather than the previous norm of entire user experiences built with Flash. I, for one, welcome this change. I may be a Flash developer, but that doesn’t mean I want to visit websites built entirely with Flash.

True, there are still many big name companies out there that want “edgy” websites built using Flash. Increasingly, these high-profile websites are realizing that the search-ranking advantages of an XHTML/CSS website often outweigh the so-called “edginess” of a pure Flash website.

Let’s say, for example, that you’re a site developer using standards compliant XHTML. Some Flash developers have just delivered you a small, lightweight MP3 player written in Flash. The advantage of having an MP3 player built in Flash is that it can be embedded within an XHTML page. The user can listen to songs and have the same rich user experience offered by a stand-alone media player, all without leaving that particular page. Great, right? It would be, but it’s your job to integrate this MP3 player into the XHTML environment that makes up the rest of the site.

The rest of the site is entirely standards compliant code. You’ve even validated all the URLs against the W3C validator. You’ve spent considerable time working around the intricate browser quirks. In short, the code works in every browser and is all valid XHTML. Beautiful.

Now, lets throw the Flash monkey wrench into the works and see what happens.

Embed versus Object

Let’s say your Flash developers have sent you an .fla file and left all of the embed code up to you. You open the .fla in Flash and publish an .swf file. You also publish an HTML file, which is ridiculously easy. Just check the “Publish HTML” box and Flash does the rest. You end up cutting and pasting the results out of your newly minted HTML file into your existing XHTML page. The code Flash gives you looks something like this:

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"  
codebase=",0,0,0" width="550" height="400" id="myMovie"  
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="myMovie.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="myMovie.swf" quality="high" bgcolor="#ffffff"  
width="550" height="400" name="myMovie" align="middle"  
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"  
pluginspage="" />

Ugly but functional. Except … except now your site doesn’t validate with the W3C validator. In fact, your code is no longer standards compliant. Why? Well the W3C’s XHTML specifications don’t allow the <embed> tag. But Netscape-flavored browsers need the <embed> tag. To understand why the <embed> tag wasn’t included in the specification, we need to look at the history of the <embed> tag.

Dreamed up by Netscape long ago in a galaxy far away?. Actually, they just made it up out of nowhere. Supposedly, they did so to provide a generic method of dealing with the proliferation of plug-in technology circa 1998. Fortunately, the days of a zillion plug-ins are gone. Flash alone seems to have survived the plug-in wars (Okay, there are some others, but they aren’t relevant here). In Netscape’s thinking, the <embed> tag would have been a generic solution. Its parameters would tell the browser how to behave using name/value attributes. Neither Microsoft nor the W3C liked this idea. They both liked the <object> tag, which is also nice and generic and does the same thing.

Unfortunately for Netscape, their lovely little idea was not included in the XHTML specs, so no valid code for you, loyal Flash users. But the whole rest of your site validates, so why this one annoying bit? Obviously, Your flash embed code also has the <object> tag in there, so perhaps we can just cut the <embed> out and use <object>?

You could do that. It wouldn’t work very well, but you could do it. The problem is that the <object> tag, while valid XHTML, isn’t understood by Netscape-based browsers. Internet Explorer knows what to do with the <object> tag, but what is the point of adhering to standards if your target audience is only IE users?

Is there another, XHTML compliant way to embed Flash content? As a matter of fact, there are two methods that will work. One is known as the Flash Satay method. Flash Satay essentially uses just the <object> tag and works around its limitations by using an empty container movie that then loads the main movie. It’s a decent way of going about things and has its uses. But there is a way that’s even better.

JavaScript to the rescue

Flash Satay is great. It provides us with some standards compliant ways to display Flash movies. But what about detecting the Flash player in the first place? And then there is another issue: search engines. What if we could embed our movie in a standards compliant manner (which search engines seem to favor), detect the player version on the user’s machine, and provide alternate content for search engines and users without Flash all at the same time? Que bueno, yes? Well you can have your banana and eat it too, thanks to Geoff Stearns. Mr. Stearns has written a JavaScript class that replaces an XHTML <div> tag with a Flash movie.

It works like this: We call the JavaScript function, passing our <div> tag as a parameter. The function then parses the XHTML and finds the tag in question. It replaces everything within that tag with the Flash movie we specified in the function call. This allows us to have actual, indexable content in that <div> tag. That means that search engine robots, users without Flash, and users without JavaScript can still see an approximation of the original content.

Stearns’ site contains complete instructions on how to use the JavaScript class, but I’ll walk through it rather quickly.

Publish your Flash .swf file as you normally would. Create your lovely, validly coded XHTML document and its accompanying CSS rules. Copy the file you downloaded called flashobject.js to wherever you keep you JavaScript files (I keep all of my JavaScript files together in a directory on my site named js). In the <head> tags of your HTML document, include the external JavaScript file we downloaded.

 <script type="text/JavaScript"  

Now, figure out where you want to put your Flash movie on the page and add a <div> tag. Something like this, taken from Stearns’ example:

<div id="flashcontent">

Everything in this will be replaced by the Flash content.
Place your alternate content here and users without the Flash plug-in  
or with
JavaScript turned off will see this.
Include a link to <a  
href="flashobject.html?detectflash=false">bypass the  
detection</a> if you wish.


Now you just need to call the function contained in the flashobject.js file. The code looks like this:

<script type="text/JavaScript">
     // <![CDATA[

     var myMovie = new FlashObject("myMovie.swf", "myMovie", "300",  
"300", "7", "#FF6600");
     // if your movie is using flashVars parameters you can still do that
     // using this syntax:
     myMovie.addVariable("flashVarName", "this is passed in via  

     // ]]>


The biggest and best advantage of this method, at least to my thinking, is its reusability. I use this code extensively on my blog. All my pages are generated from templates, so if I point to the flashobject.js file in my <head> tag template, I automatically have site-wide access to the script. Because my templates are themselves created from smaller chunks of code, I can have two versions of my <head> tag template; one with the code and one without. Whenever I want to add Flash to a page, I just change templates and I can add Flash content without breaking the validator.

Of course, I still have to include a <div> tag and call the function, but that’s the easy part.

And there you have it: a standards compliant way to add Flash to your XHTML.

Introducing sIFR

Now let’s imagine for a moment that you are a purist. You love strict XHTML as only a mother can. Let’s suppose you’re as rabid about your little baby’s standards as Diane Ladd in “Wild at Heart.” How could we convince you that there is a practical application for Flash files, even in your twisted, lipstick-smeared world?

Well, we would criticize your typography of course. We already know your code is impeccable, but wow. Those headlines are still in Georgia huh? Kind of primitive, don’t you think?

As web designers, we have reliable access to maybe six fonts that all users will have. This was one of the limitations of HTML that first drew me to Flash. Now, you may not be as obsessed with typography as some of us (if you know that Mrs Eaves is not Mr. Eaves wife, then you might be obsessed with typography), but wouldn’t you like to use something other than Arial sometimes?

Well, I can’t really help with the body text. But headlines, oh headlines, do I have a revolution for you. It’s called sIFR.

First, a brief history. SIFR is not exactly a new idea, rather an improvement on an old one. Web designers have always disliked the limited selection of fonts available. The problem is that in order for a browser to render a font, that font must reside on the user’s hard drive. How many universally available fonts are there? Well conservatively, probably about six: Verdana, Times, Arial, Helvetica, Courier, and Geneva. Trebuchet, Tahoma and Lucida are also widespread, but less so than the Big Six. If you’re using stylesheets, you know that the only options for total compatibility are simple sans or serif declarations. You declare a sans-serif font for a block of text and it’s the browser’s decision as to which sans-serif font it uses to display the given text.

From a designer’s standpoint, this situation is undesirable to say the least. So, way back when, some folks thought, “Hey, we could replace a headline with a graphic that has the same text, but as an image. That way we can exercise control over the typeface being used. We can use any typeface because it’s an image.”

While a solution, this is still less than ideal. For one thing, it means that every single headline must be generated by hand using some sort of image application. Even if you automate the creation process with scripts, this is impractical for all but the simplest of sites. Today’s database driven, content-assembled-on-the-fly website engineer cannot afford to create a separate image for every single headline.

There is another problem. Actually there are several others, but the biggest one is that this technique effectively ruins the site for the visually impaired. Instead of tags that look like this:

This is my great headline’

You need something like this:

<img scr="mygreatheadline.jpg" alt="This is my great headline">

A screen reader is going to read that whole second line aloud, and the person using it is going to be annoyed because you were too caught up in the appearance of the text to remember that lots of people don’t care about the appearance.

So, allow me to introduce scalable Inman Flash Replacement. Yes, sIFR stands for scalable Inman Flash Replacement. The technique takes its name from the man who invented it, Shaun Inman. The scalable part was added by Mike Davidson, who improved on the original and maintains the current code. The technique is essentially the same as image replacement, but relies on JavaScript and Flash to dynamically replace XHTML text with Flash text.

Why is this better? Many reasons. Foremost, sIFR allows us to code our pages as we normally would. We can create a stylesheet and set the size and other parameters of a headline. With sIFR on the page, something amazing is going to happen. When the browser requests the page, a JavaScript class parses the page for a given variable and replaces it. In our example, we’ll say that the element we want the replace is an <h1> tag, but it could be anything. Wherever the JavaScript finds that <h1> tag, it sets the text contained within the tag to “hidden” and then embeds a Flash movie matching the element’s original size. The script then feeds the Flash movie the hidden text. Finally, like magic, the Flash movie displays the text it gets from the JavaScript.

There are no restrictions for which fonts we can and can’t use within a Flash movie, so we can design our headlines however we’d like.

If the user doesn’t have Flash, doesn’t have JavaScript enabled, doesn’t have either, or is using some assistive device, the original text is still there just as it would have been had we done nothing at all.

How and when to use sIFR

Mike Davidson, who maintains the code for sIFR, has excellent instructions on his site for how to use the code. For the sake of clarity, I’ll walk through a quick example here.

To get started, download the .zip file containing the script. The package also includes the Flash movie template. Open the Flash template and double click on the movieclip that occupies the main stage. This will take you to the actual text box. Just change the font for text box to whatever font you want to use and publish the movie. Upload the resulting .swf file to your site.

Now we need to add sIFR to our XHTML and CSS files to make it work. The first thing to do is include the JavaScript using the <head> tags of XHTML. See our earlier example of the MP3 player for the syntax. Next, open the JavaScript file sifr.js. Near the very bottom of the file, you’ll see a function call that looks like this:


Just below that line, we’re going to add another function call. The syntax is explained in the readme file that accompanied your download. The code I use on my site looks something like this:


 sFlashSrc:"", sColor:"#FEDB18",


This calls the JavaScript function replaceElement. The sSelector parameter tells the function which tag to replace. The sFlashSrc parameter tells the function where to find the Flash movie. The sColor parameter controls the color of the font and sBgColor controls the background color of the Flash Movie.

In the example above, all the <h1> elements will be replaced. We could get more specific. In fact, you can be as specific or generic as you like with the sSelector parameter. Let’s say for example that we only want to replace <h1> tags that occur in a <div> named body. We would just change our code to read:

 sIFR.replaceElement(named({sSelector:"#body h1",


 sColor:"#FEDB18", sBgColor:"#6f5f45"}));

There are additional parameters that you can pass to the function to control things like hover states for links, transforming text to uppercase, and more. For a complete list of parameters, see the documentation packaged with your download.

Putting sIFR on the page

The next step is to include the sIFR classes in our CSS file. Open your CSS file in a text editor and add this code:

 .sIFR-hasFlash h1


 visibility: hidden;


 .sIFR-flash { visibility: visible !important; }

 .sIFR-replaced { visibility: visible !important; }



 position: absolute;

 left: 0;

 top: 0;

 width: 0;

 height: 0;

 display: block;

 overflow: hidden;

 letter-spacing: 0;


This chunk of CSS does a couple of things. First, it creates a hidden selector class for the element we are going to replace. Then, the rest of the declarations handle the display of the replacement movie.

The primary thing were going to do with this code is use the class .sIFR-hasFlash h1 to control the size of our replacement text. The creators of sIFR refer to this as “tuning” your fonts.

This tuning process can be a little tricky, and is essentially a process of trial and error. The goal is to make the original text the same dimensions as the replacement text. To do so, we can add declarations like line-height, font-size, font-weight and margin or padding to the .sIFR-hasFlash h1 declaration. Unfortunately, there is no general solution I can give you. Some situations require more tuning than others.

If you open up the sifr.js file again and look near the bottom, just above where we inserted our function all earlier. You should see a function that reads:


Comment out that line and add this one just below so you have:



This will allow you to see your tuning in real-time. When you’re done, just uncomment the .setup() line and comment out the debug() line.

The only other thing you’ll want to do is change your print-css stylesheet to make sure your replacements don’t happen when the user prints the page. If you’re having problems refer to the sIFR wiki for troubleshooting and more detailed instructions.

There might be a temptation, given this newfound control over fonts, to go a bit crazy and use it everywhere. Resist that temptation. sIFR wasn’t designed to replace everything on the page. Your body text is still going to be limited to the big six. sIFR is best used for headlines, and maybe subheadlines if you don’t have too many.

One thing you may notice is a slight lag time before your headlines are displayed. On my aging G3 iBook, this little pause is about one to two seconds. Presumably, on new equipment it would be even less. If this bothers you, you can set sIFR to show the normal font before it replaces it with Flash.

I should note that you do not have to put the function call in the sifr.js file. In fact, sometimes you may not want to. You can also write it into the XHTML as we did with the earlier script. I think it makes more sense to put it in JavaScript file itself because I use the same headline throughout my site. However, if you wanted to use different fonts on different pages you would need to call the function from each page.

If you ever get stuck using sIFR, refer to the documentation or the wiki. And of course, nothing beats trial and error.

Achieving Perfect Harmony

Well there you have it. Two ways Flash can peacefully co-exist with XHTML in this newfound world of web standards. At the same time, we’ve tackled one of the most persistent issues for all web designers: how to get cool fonts on your site.

If you would like to see both of these techniques in action you can visit my personal site, Note that the Flash Object part of my site requires the Flash 8 player.

sIFR is all over the place these days. You can look at the official example page or some bigger sites like ESPN or CBS News. It’s not always easy to tell when either of these techniques are being employed, and that’s kind of the point. If you don’t notice the behind the scenes stuff, then you are witnessing a truly seemless integration of XHTML and Flash.

Adhering to web standards is no longer an excuse to avoid Flash. At the same time, don’t use these techniques to justify doing a whole site in Flash. Flash has its place. It does some things very well and other things are best left to XHTML.

Build an Embedded MP3 Player in Flash

In my last article Use Web Standards With Flash, I mentioned that Flash is most useful for building small player applications that present audio and video content. Today, I’d like to dive a little deeper into this idea and present a technique for playing MP3 files in a browser window.

Say you have created some audio files that you are really proud of. So proud, in fact, that you’d like to include these songs on your site. Now, in pure HTML and CSS, you can provide beautifully styled links to each of your MP3 files. Lovely, except that each time a user clicks on a link, he leaves the page that lists the links to all of your other songs. Instead, he gets a nice, pure white browser window with the little Quicktime toolbar.

What’s wrong with that? Well, not only can the user not immediately access the other songs you’ve posted, but there may well have been additional content that the user wanted to read while listening to your truly stunning audio files.

Before we jump up and say, “Oh yes – let’s use Flash,” we should consider other alternatives. The first thing that comes to my mind is Windows Media Player. Windows media files can be embedded in a page, and, through the use of JavaScript, you could even build a dynamic menu. But then you run into the tricky problem of cross platform support for .wma files. At least, the embedded stuff never seems to play correctly on my Mac. Also, presuming you are starting with MP3 files, you’ll need to re-encode your music before you post it. Not to mention the fact that many people don’t have Windows Media Player installed at all. Then there’s Real Player, which has some advantages such as better cross-platform support, but still requires an extra step of running your audio through another encoder.

So, we want a solution that lets us post regular old MP3 files and play them in a browser using an embedded interface. If I may, I would suggest that Flash is an excellent choice in this situation.

Using the embed techniques discussed in my earlier article, we can offer users a simple interface built in Flash that allows then to listen to audio without leaving the page. A number of Webmonkey readers wrote to say they like that idea and wondered if I might write a tutorial on actually building an MP3 player. So, today I’ll show you how to make a Flash MP3 player with a very simple play/pause button. The resulting file will weigh in at a paltry 4KB. You can embed the player on your page and allow users to listen to your audio content (podcasting anyone?) without leaving the page. I won’t go into the complete detail necessary to create a full blown iTunes-type Flash jukebox, but I’ll offer a few suggestions for how you might go about doing so. First, we’ll start with the bare bones necessities of playing MP3s in Flash, namely the ActionScript class Sound.

What you’ll need
•Adobe (Former Macromedia) Flash
Pushing buttons
Before we get started with the sound object itself, let’s think about the most stripped down possible MP3 player. What exactly do we need to present the user with? I’m going to go out on a rhetorical whim and say that its possible to use simply one button, or rather, two buttons in one. Namely, a play button that toggles itself back and forth between “play” and “pause” depending on the state it’s in. In other words, when no sound is playing, it appears as a play button to tell the user that pushing it will play some audio. Once the user pushes it and the track starts playing, our button will turn into a pause button. And that’s it. It’s small, lightweight, and offers the bare essentials of what the user needs.

Let’s get started. For the examples in this article, I’m using the most recent version of Flash, which is included in Macromedia Studio 8. There’s a demo available for download at Macromedia’s site if you don’t already have the software.

Open up a new Flash document and create a simple play/pause button using whatever design you would like. I modeled mine after the iTunes interface since it’s a fairly popular cross-platform application that most people will recognize. Hopefully, Apple won’t think I’m stealing their idea. I just happen to think that, when it comes to user interfaces, repetition and familiarity are good things.

Create two graphics, one for the play button and one for the pause button. Put the play graphic on the stage and resize the stage to match the dimensions of the graphic. Next, turn the graphic into a movieclip and give it an instance name of “play_mc.” Then, put the pause graphic on a new layer on top of “play_mc” and turn the pause graphic into a movieclip with an instance name of “pause_mc”.

The last thing to do is create an invisible button to place over the graphics. To create an invisible button, just choose “New Symbol” from the “Insert” menu, choose “Button” for the type and give it a self-explanatory name like “invis_btn.” Then, you will be taken to the button’s timeline. Insert a keyframe in the “hit” frame and draw the shape you want for your button. In this case, I drew a circle.

Go back to the main timeline and drag your new button out of the library and onto the stage. At this point, you should see a pale blue shape on the stage. This shape won’t show up when you publish your movie, it simply allows you to see the active area of the button. Give the button an instance name of “trigger_btn.”

Here is a screenshot to give you an idea of how things are looking so far.

Hit me with music
The next step is to write some pretty basic code. Some people would even consider this the “fun part.”

Create a new layer on your main timeline and label it “actions.” Select the first frame and open the Actions panel.

OK, now hold up for a minute. Before we get down to the actual code, let’s think about what we need our bare bones MP3 player to do. We need to load an MP3 file, and then we need to play and pause that file. Pretty basic, right? Luckily for us, the good folks at Macromedia have given us a built-in Class to handle sounds. Naturally, it’s called Sound. It’s already part of ActionScript, so all we have to do is create an instance of the Sound class and assign the controls to our invisible button. But first things first. Let’s add a line of code to set the initial state of our pause button to hidden.

pause_mc._visible = false;

We are going to present the user with a simple play button which, when pressed, will start playing an MP3 file. We need to write a function to load the MP3, a function to stop the MP3 and a function to start the MP3. Now, because we’re using one button to both play and pause, we’ll need a fourth function to act as an intermediary to determine whether the user wants to play or pause based on the current state of our sound. Here are the four main functions we’ll use to control our MP3 player. Copy and paste this code into the first frame of the actions layer:

function getSound(url:String) {


delete sound;

sound = new Sound();

sound.onLoad = function(success:Boolean) {

if (success) {

trace(“[MP3 Player]:file loaded”);

} else {

trace(“[MP3 Player]:Could Not load Sound Data from file,

please try again”);



sound.loadSound(url, true);


function audioStop() {


$marker = sound.position/1000;

$state = false;


function audioPlay() {


$state = true;


function checkState() {

if ($state == true) {

pause_mc._visible = false;


} else {

pause_mc._visible = true;




Now let’s go through each function and examine what’s happening.

The getSound(url) function is what initially loads the MP3. It takes one parameter:a string representing the path to the actual MP3 file.

The first thing we do in this function is stop the sound object and then delete it. Now why would we stop and delete an object we haven’t even created yet? Well, in the future, you may want to write some code that calls this function to load a second MP3. The sound object is quite happy to load several MP3s on top of one another and play them all simultaneously (as you might want to do in video game, for instance). However, for our purposes, this is no good. So before we create the sound object, we make sure we destroy the old instance if one exists.

Next, as the third line says, we create a new sound object. In the code, I have chosen to give the sound object the rather uncreative name “sound.” The Sound class that’s built into ActionScript has some standard methods such as onLoad(). In this case, I haven’t really done anything with the onLoad method other than trace some output so you can see whether or not your MP3 has loaded when you test your movie. However, if we were making something more complex, we might actually have some code that is triggered when the sound object finishes loading the MP3.

There are some other handy methods that come with the sound object. onSoundComplete(), for instance, triggers an event when the sound file is finished playing. This can be very handy for something like a jukebox type application where you want to move to the next sound as soon as the current one finishes.

The next line we’re going to look at uses the loadSound() method. The Sound class has some other methods as well. See the ActionScript reference panel in Flash for more details.

After the onLoad method, we have the meat of the function. The line sound.loadSound(url, true); is what actually loads the MP3. This method takes two parameters. The first is the path to the MP3 file, with which we pass on the variable “url” from our function parameter. The second parameter of loadSound controls whether or not the sound is “streamed.” I think this is poor semantics on Macromedia’s part since this does not really control true streaming. This parameter simply controls whether or not the sound starts playing as soon as it can or waits until the entire file is loaded before starting to play. True streaming, (i.e. not downloading), requires server side software and is way too complicated to get into in this article. While it may appear that our MP3 is streaming since it starts playing right away, it’s really just downloading into the user’s browser cache, which true streaming media does not do. So, despite the poor word choice, we want our sound to start playing as soon as it can, thus we set the parameter to “true.”

Alright, we’ve gotten the MP3 to load and to start playing as soon as it can. On the next page, we’ll look at the rest of the code, including that good ol’ button magic.

Make it stop (and start again)!
Onward! Referring back to the code on the previous page, we’ve already demonstrated how to load our file and get it to start playing.

The next two functions are the audioStop() and audioPlay() methods. These methods will be triggered by the fourth function. They are essentially wrapper functions for the Sound class’ built in Sound.stop() and Sound.start() methods. However, our functions do one additional and very important thing:they control the state of a Boolean variable (a variable that can either be true or false) named $state. I have added the $ prefix to the variable name because, were we creating a custom class out of this code, $state would be what’s called a class variable. It’s sort of a programming convention – at least in Java – to prefix class variables with a dollar sign. If it bothers you just pick a different name, but don’t simply call it “state” without the $, which happens to be a reserved word in ActionScript. This variable is the logic of our code. It keeps track of whether or not the MP3 is playing and allows our last function to determine whether or not the user is trying to play or pause the player.

You might notice that audioPause has an additional line of code that sets a variable “$marker”. This variable keeps track of where the playhead is resting. The built-in function Sound.start() can take a position parameter like so:Sound.start(position). If the position parameter is left undefined, then the track plays from 0, or the beginning. This is obviously not what we want. If our user is near the end of the track and pauses it to go make a banana split, when he returns and hits play, he does not want the sound to start over from the beginning. So, we need to find out where we are when the user presses pause. To do this, we will grab the read-only parameter Sound.position. For whatever reason, this parameter is read in milliseconds, but the Sound.start() method expects a number in seconds. Solution? Divide by one thousand.

The last function we’ll use is called checkState(). This will be the function that our button calls when it is pressed. All this function does is check to see whether our sound object is currently playing or not. It then acts accordingly to change that state by calling either audioPlay() or audioStop().

OK, those are the major functions. Now, we just need to add a few lines at the top of all this to initialize our variables and call our functions. Cut and past the following lines of code into frame one of the actions layer. It doesn’t really matter if put it above or below the prior code.



var $state = false;

var $marker = 0;

trigger_btn.onRelease = checkState;

So, what does it do? The first line here calls our getSound function and passes it the path to the MP3 file on the server. Next, we tell our sound object to stop playing. So it finds the file, starts to load it, tries to play it, and then gets told to stop. This line is up to you. I don’t like pages that automatically start playing sounds at me, so I make the starting of the sound a user action. But you may want to take it out, because if the user doesn’t press the play button, they’ll never hear anything. If you want the sound to start automatically, just omit this line and change the next line to var $state = true;.

Why not just make the play button start the whole loading process you ask? Well, I like to initialize the loading in the background. That way, by the time the user gets around to actually pressing the play button, the whole file may be loaded and the user experiences no load time at all. The code that controls this sets the $state variable to “false” since the sound has been stopped.

Next, we create the $marker variable and set its value to “0”. We do this because the first time the user pushes the button, we want the sound to start from the beginning. The last line sets our invisible button’s release event to the function checkState.

Pretty simple, eh? Let’s look at some of the more heavy duty features you can add to this simple player.

Save time for a slow dance
And there you have it, a quick and extremely simple MP3 widget you can drop into your page.

Now, for those of you looking to build something a little bigger and slightly more complete, I have a few suggestions. The Flash Sound class does not have built in fast-forward or rewind methods. The best way to add this functionality is by using the setInterval method of a movieclip.

Create a button and attach a setInterval call to its onPress event. Set the interval to call a function ff() which will fast-forward the track. I’ve found that an interval of 500 milliseconds produces the desired effect without disorienting the user. Next, you need to clear the interval with the release event of the same button. As for the ff() function itself, you might want to consider using sound.position much as we did earlier for our $state variable. In this case, you would want to find the position of the playhead, stop the track, advance the playhead and then restart the track. Something like this will work with what we have so far:

function ff () {

var old = sound.position/1000;


new = old+5;



Another feature you might want to add:volume controls. You could use simple buttons or get fancy and use a sliding bar. Both of these are left as exercises for the reader, but I will tell you that the Sound object has two built in methods called getVolume() and setVolume() which should help get you started.

We also shouldn’t overlook the question of playing multiple tracks within the same movie. There are about a dozen ways you could handle this, though from my own experience a separate XML file is usually the way to go. Just load the XML file into Flash and parse out the info you need. Include the path to the file, the title, artist, album, and any other information you’d like to display. Finally, just pass the path along to our getSound() function. This works very nicely if you’d like to add a podcast link to your site, since podcasts are RSS files and RSS is really just XML.

As you can see, it’s possible to make some very fancy MP3 players using Flash. In fact, you can recreate just about all of the functionality of popular desktop players like iTunes or WinAmp using only Flash and ActionScript. Hopefully, this article has allowed you to develop a very simple way to give your web audience some music to listen to – and whetted your appetite to perhaps build a full-blown audio application.

General Information about Free Flash MP3 Player

Free Flash MP3 Player offers free software applications and reviews of other free MP3 players that allow you to play music on your myspace account or website. We also rate each MP3 player saving you valuable time. Also we will let you know which website and products that can be trusted (virus-free & spy ware-free).

Our criteria for MP3 players is that it must be easy to use and install. So easy that you don’t have to be a programmer to embed it into a website. Ideally the MP3 player should automatically scan a specified folder and develop a play-list.