Flash Explained

Learn Flash easily.

Making a simple player for mp3 loops with a visual equalizer

October 14th, 2008 | Author: Luka | Category: Sound

I have received many requests to explain how to create an mp3 player in Flash, so here it is! You will learn to create the following (please note that this is a Flash 8 tutorial):

  • A visual equalizer with colored bars,
  • A Sound object for external mp3 loading,
  • A play / stop button for your users, to turn the music and the equalizer on and off,
  • How to make your mp3 player a part of your Flash or HTML site.

You can see the player in action below this paragraph! Click on the stop and play buttons to see how easily a user can switch the music on or off. The is just a proposed design. Once you learn how to create this kind of a player, skinning it and making it blend in with the rest of your site design is an easy task.

Designing the equalizer

1 Open a new Flash document. Press Ctrl+J (or select Modify > Document). Set the Frame rate for your movie to 30 frames per second (fps). Click OK.

Document properties window in Flash 8.

2 Select the Rectangle tool (R). Block out the stroke color, because you need to make a borderless rectangle. You can block the stroke color by going to the Color part of the Tools panel, clicking on the small pencil icon The stroke color button in the Tools panel. and then clicking the block color button The button for blocking a color.. As for the fill color, choose some darker hue that is in good contrast with the white backgorund of your movie.

3 Draw a small narrow rectangle (see 1 in the image below). Select it with the Selection tool (V) – see 2.

The four steps of setting the exact dimensions for a rectangle with design tools in Flash.

In the left side of the Properties panel, enter the dimensions for the rectangle manually: 4 pixels in the width (W) field and 22 pixels in the height (H) field (see 3 in the image above). Make sure that the little padlock icon is unlocked so that you can adjust each dimension independently of the other one.

Unselect the rectangle by clicking anywhere on the stage (4).

Also, see to it that the rectangle’s position on the stage is set to round numbers. The values in the X and Y fields (next to W and H) must finish with zero. You must do this if you want your rectangle to be displayed clearly and sharply on the screen.

4 Go to the Color mixer panel (Window > Color Mixer). Click on the little paint bucket icon to select the oprions for the fill color. In the Type menu (still in the same panel), select Linear as type of gradient.

Selecting the linear gradient for the fill color in the Color mixer panel.

5 Add three more color squares in the linear gradient stripe on the bottom of the panel. You can do this easily by just clicking with your mouse between the existing ones.

Adding more color samples to the linear gradient.

6 Now, click on each of the small squares and enter the hex color value in the appropriate field, in the order indicated on the image below:

All the hexadecimal color values for the linear gradient.

Also, move the three middle squares so that they are ordered as the image shows. Just click and drag them left or right, as needed.

7 Zoom in on the small rectangle on the stage with the aid of the Zoom tool (Z), to work more easily.

8 Select the Paint bucket tool (K). Click on top of the rectangle and while holding Shift drag your mouse down. This will create a perfectly vertical linear gradient fill.

Painting the rectangle with a nice linear gradient fill.

9 Select the rectangle with the Selection tool (V). Press F8 (or select Modify > Convert to Symbol). In the Convert to Symbol window that appears, select Movie clip as type, call it equalizer bar 1 and click OK.

Choosing the options for a new symbol.

10 Double-click on the newly created movie clip on the stage to enter inside it. You can know if you are inside a symbol or not by looking at the information displayed above the stage.

The current timeline information.

11 Call the first layer inside this movie clip colored rectangle.

Naming layers inside a symbol.

12 Right-click on frame 40 and select Insert frame from the menu that appears.

Prolonging the duration of a keyframe in Flash.

13 Lock this layer and create a new one, then call it mask. Click on its first frame to select it for working.

Making the second layer inside the movie clip symbol.

Top of page

Creating and animating the mask for the equalizer bar

14 Select the Rectangle tool (R) again. Turn off the Snap to objects option The Snap to objects icon turned off. in the Tools panel to work more easily. Choose any flat fill color you like and leave the stroke color blocked. Draw a rectangle that is slightly larger than the colored one below it.

Drawing a bigger rectangle above the existing one.

15 Right-click on frame 40 of this layer and select Insert Keyframe (not frame!).

Inserting a keyframe into the mask layer.

16 Click anywhere (standard left click) between the two keyframes on the mask layer.

A simple frame selected.

Go to the Properties panel and select Shape from the Tween menu.

Choosing a shape tween for the current layer.

You have just created a shape tween animation, although there isn’t any movement present yet. This particular kind of animation is represented by a continuous arrow between the two keyframes, on a pale green background.

A shape tween animation in the mask layer.

17 Right-click on frame 10 and insert a keyframe.

Inserting a new keyframe for the first section of the animation.

18 Select the Free Transform Tool (Q). Click on the rectangle, you’ll see the handles for transforming appear. Click on the top middle handle and drag it down almost to the bottom.

Making the mask rectangle smaller.

19 Insert another keyframe at frame 18. Stretch the rectangle, but not all the way to the top. If you shrinked it down completely in the span of ten frames, you mustn’t stretch it completely now, because the movement wouldn’t look so realistic.

The rectangle at three-fourths of its original size.

20 Do the following: insert five more keyframes and resize the rectangle accordingly. I did it like this:

Adjusting the height of the mask rectangle according to the placement of the keyframes.

There is still a small adjustement to make if you want your animation to play out smoothly. If you click on the first and last keyframes of the mask layer, you’ll notice that they are the same. This is normal, because when you insert a keyframe, Flash copies all the contents from the previous one – they’re identical.

So, when the animation plays, even if it is a fast one (as is the case with this movie, for which you set the speed at 30 fps at the beginning of this tutorial), there will be a small “pause”. Why is that? Because in Flash an animation loops endlessly unless you tell it to stop via ActionScript.

So when this shape animation comes to the last keyframe, it goes back to the first one and continues looping. Since the last and the first keyframes are the same, and they follow one after another, you have a portion of the animation repeating. And in that moment, it seems as if the animation has stopped for a fraction of a second. To avoid this, do the following:

21 You won’t change the shape of the rectangle, there’s an easier way to smooth out your animation. Right-click on frame 39 (the one just prior to the last one) and select Insert Keyframe.

Then click on the newly created keyframe and drag it over the keyframe 40.

Replacing a keyframe with another one.

You have just replaced the last keyframe with the one preceding and therefore made your animation more smooth. Remember this technique, it can also be applied to motion tween animations.

22 Finally, lock the mask layer. Right-click on this layer’s name and select mask from the menu. The colored rectangle layer beneath it has just become masked by it.

Masking a layer.

23 Test your movie (Ctrl+Enter). You’ll see the equalizer bar jumping up and down happily :) You may have wondered why did you have to animate a mask instead of the colored bar directly?

Well, the mask is animated because in this way the equalizer bar behaves as it does in music programs and on hi-fi sets. As you probably noticed, the red color is always at the top, indicating the full power for a certain sound frequency. If you didn’t animate the mask, but the colored bar directly, the gradient would stretch also. And this is bad, because, as I said, in real life this isn’t so. If the bar is, say, at 25% of its size, you never get to see the red color, but only the green tones. Look at the parallel examples below to see what I mean. Or turn on WinAmp if you have it installed on your computer, play a song and look at the equalizer bars and the way they behave.

24 Before you move on to duplicating this bar, you will make a small change to it so that you can easily change the way it looks later, if you ever decide to change its appearance so that it fits into your overall website design better.

Close the movie preview window and return to your Flash document. Hide the mask layer and unlock the colored rectangle layer. You have to hide the mask, otherwise you wouldn’t be able to see the masked layer below it.

Hiding the mask layer and unlocking the one beneath it.

25 Select the colored bar with the Selection tool (V).

Selecting the colored equalizer bar.

26 Select Modify > Convert to Symbol. This time, select Graphic as type of symbol, call it color gradient bar and click OK. This won’t affect your animation. This will save you a lot of work if you want to change your equalizer’s visual appearance later. All you have to do is enter inside the graphic symbol you just made, by double-clicking on it inside the Library, place in some other colors, design, and you’re done!

Always strive to make your Flash projects more modular and flexible. You never know when you (or more importantly, your client) will need to make some changes to your document. And by having easy access to various parts of your movie which are independent from one another, you can save a lot of time. Also, be sure to save your document under different names, like myproject001.fla, myproject002.fla, as you progress in the building of your Flash website, banner or anything you are working on. You never know when you might need to revert to a previous stage of your document. So, save this movie you’re working on now!

Top of page

Duplicating the equalizer bar

27 Open the Library (Window > Library). You’ll find your equalizer bar 1 movie clip and the color gradient bargraphic symbol inside.

Right-click on the equalizer bar 1 movie clip and select Duplicate. Call the new symbol equalizer bar 2 and click OK.

Duplicating a symbol inside the Flash Library.

28 Double-click on the newly created equalizer bar 2 movie clip in the Library to enter inside it.

29 Unlock the mask layer. Select frames 2 through 41, right-click on them and select Remove Frames. Right-click on frame 68 and select Insert Keyframe. A shape tween should appear. Then insert ten more keyframes between the two existing ones and make different changes to the mask rectangle, as shown in the image below.

Making the shape tweens inside the second equalizer bar movie clip.

30 When finished, go back to the Library and duplicate the equalizer bar 1 movie clip two more times. Call the new symbols equalizer bar 3 and equalizer bar 4, respectively.

All the symbols made so far in the Library.

31 Double-click on the newly made movie clips in the Library and make changes to their timelines and animations too. Here’s what I made – this is a suggestion only, you can modify your animations as you deem appropriate.

The timelines of the last two equalizer bar movie clips and their animations.

Why all these changes? Well, here is the reason: for example, when the first movie clip (equalizer bar 1) reaches its last frame of animation (40), the second one (equalizer bar 2) still has about 24 frames until it’s own animation end. Then the looping begins. The animation of the second movie clip goes back to frame 1, and the first movie clip is already on frame 24 of its own animation.

What this results in is that you have four movie clips with different durations of their animations. The bottom line is that you will always have a random animation for your equalizer going on. This is great, because it looks completely realistic. Sure, at some point, all these animations will find themselves at the same positions they all started with, but it will take a long time until this happens and also, the user won’t notice this.

These simple changes make for a great visual effect! As you can see, with little changes to your document you can achieve nice things for your website. In my opinion, in Flash there is almost nothing that’s impossible to make.

You will now proceed to put all these equalizer bars together and make your music player a movie clip.

Top of page

Creating the music player movie clip

32 Whichever equalizer movie clip you are now inside, click on the Scene 1 link above the layers to return to the main scene.

Returning to the main scene.

33 Double-click on the Zoom tool The Zoom tool icon in Flash. in the Tools panel to set the zoom factor to 100%.

34 With the Selection tool (V), click once on the equalizer bar 1 movie clip on the stage to select it. In the Properties panel, make sure that it’s coordinates are set to round numbers (see step 3 of this tutorial for an explanation on how to do this).

35 Select Edit > Copy to make a copy of this movie clip.

36 Select Edit > Paste in Place to paste the copy you just made exactly in the same place as the original one.

37 Don’t click anywhere now, so that the copy of the movie clip stays selected. Just press the right arrow key on your keyboard 7 times to move this movie clip exactly by 7 pixels to the right.

Two identical instances of the same movie clip spaced by 7 pixels.

38 Repeat the previous operation twice: make two more copies of the same movie clip and move them 7 pixels to the right of the last one. In the end, you should have four movie clips on the stage, with seven pixels of space between them.

Four movie clip instances spaced equally.

But, these are the instances of the same movie clip – equalizer bar 1. And you have four different equalizer bars in your Library. How to put them here? Easily.

39 Click once (not twice, because you’ll enter inside it, which you don’t want now) on the second movie clip from the left with the Selection tool (V).

In the Properties panel, click the Swap button.

The Swap symbol button.

In the window that will open, select equalizer bar 2 and click OK.

Swapping a symbol on the stage.

You have just easily replaced a movie clip on stage for another one!

40 Repeat this operation for the remaining two movie clips (the third and fourth ones from the left), swap them for equalizer bar 3 and equalizer bar 4 movie clips, respectively.

41 Select all four movie clips on the stage. Just use the Selection tool (V) – click and drag it to encompass all movie clips.

All the four movie clips selected.

42 Hit F8 to convert them into a new movie clip. Pay attention: in the Convert to Symbol window, make sure to select Movie clip as type, because the selection may have stayed on Graphic symbol from before. Call the new symbol mp3 player and click OK.

43 With this newly made movie clip still selected, go to the left side of the Properties panel and give it an Instance name. Call it musicPlayer.

The Instance name of the new movie clip.

This Instance name will serve you later to tell your player what to do via ActionScript.

Top of page

Arranging the layers inside the mp3 player movie clip

44 Double-click on the mp3 player movie clip on the stage to enter inside it.

45 Call the first layer equalizer.

46 Make a new layer, call it background and move it below the equalizer layer. Just click on it and drag it below.

Making a new layer inside the mp3 player movie clip.

47 Make 3 new layers above the equalizer layer and call them button, labels and actions, respectively. Lock them all.

All the layers for content inside the movie clip symbol.

48 Unlock the background layer. Draw a rectangle (choose any colors you like) here. Its bottom part should go a little below the equalizer, because here is where the button for play / stop control will be situated in another layer.

The background for the music player.

Lock this layer.

49 Unlock the button layer. Using the Rectangle tool (R) while holding Shift, draw a small square below the equalizer. Select a fill color that will be in good contrast with the background. Also, make sure that the rectangle is placed on round coordinates. If it is difficult to draw such a small square, enter its dimensions manually in the Properties panel.

The stop button placed below the equalizer.

50 Like you did with the equalizer bars before, select the small square, copy it (Ctrl+C) and paste it in place (Ctrl+Shift+V). Move it with the right arrow key to the right. Again, after pasting the copy don’t click anywhere or your two squares will merge, and you’ll have to copy and paste it in place all over again.

Two little white squares that are soon going to be the controls for stopping or playing the music.

51 Zoom in to work more easily. Select the Selection tool (V). Make sure that the Snap to objects Snap to objects turned on.option is turned on.

Click on the right square’s upper right corner and drag it down, until you reach the middle point of the square’s right side and release your mouse. Next, click and drag the bottom right corner of the square and drag it to the point you made previously. It will snap into place, and voila! You’ve got a nice play button!

Making the play button shape.

You can zoom out now to 100% because there isn’t any more precise graphic work that is going to be done here.

52 Select both the square and the triangle.

Both play and stop icons selected.

53 Select Modify > Convert to Symbol (or press F8). Select Button as type of symbol and call it stop and play button. Click OK. Why are both the stop and play icons converted into a single button symbol? Try moving your mouse over the buttons in the Flash example below.

The clickable area of a button is defined by its Hit state (if you enter inside the button you’ll see this). Since there is no Hit state defined for this button, Flash takes the Up state of the button as the Hit area. So, the two little icons (stop and play) are the clickable area. If you move your mouse between them, the hand cursor will disappear. This is fine, because the user will think these are two different buttons. And you’ll program your player later so that this single button serves both for stopping and playing the mp3 music. Therefore, this is perfectly allright. Why make two buttons if one is enough?

54 Select this button you just made if it isn’t selected already. Go to the Properties panel and assign it an Instance name: call it playStop.

The Instance name of the playback control button.

Lock this layer.

55 Go to the labels layer (you don’t have to unlock it). Right-click on its frame 5 and select Insert Keyframe.

A new keyframe inserted into the labels layer.

56 Still on this newly created keyframe, go to the Properties panel and give it a label: call it playing. You’ll see a small red flag appear in the keyframe, on the timeline.

Labelling a keyframe.

This label serves to tell Flash where to move its playhead. Instead of telling things like gotoAndStop(5), it is much better practice to label your keyframes and then issue commands like gotoAndStop("playing"). If you ever move them, you move the label with them and you don’t have to look up the frame numbers each time. It is easier to remember a word than a number, especially if there are lots of them.

57 Click on the first keyframe of this same labels layer and give it a frame label too: call it stopped.

Two small red flags indicate frame labels in this layer.

58 Right-click on frame 5 of the button layer and select Insert frame. Do the same thing for the background layer.

Prolonging the duration of two layers.

59 Now click on the first (and only one so far) keyframe of the equalizer layer and release your mouse button. You have to do this (clicking and releasing), otherwise, you’d be selecting all the frames along once you began moving your mouse.

Now click again on this keyframe and drag until frame 5. Release your mouse. You have successfully moved the keyframe. The timeline on your equalizer layer should look like the one below.

The first keyframe of the equalizer layer moved to its new position.

The keyframe containing the equalizers has been moved because it must not be seen at the beginning, while there isn’t any music playing yet.. You will see how to make it appear, once the music has been loaded and started playing, later in the ActionScript section of this tutorial.

60 Click on the first keyframe (and the only one) of the actions layer to select it. Select Windows > Actions (or press F9) to open the Actions panel.

61 Click in the area for entering code, and type in the following command:

stop();

This action ensures that the mp3 player movie clip won’t go forward and start playing. Also, you’ll see that a lowercase “a” has appeared in the timeline of the actions layer, indicating that some ActionScript has been placed here. You can close the Actions panel now.

Actions placed on a keyframe.

62 Click on the Scene 1 link above the layers to go back to the main scene.

The link for returning to the main scene.

Ta-daa! You have just finished designing the mp3 player! All that remains is to have some actions assigned to it so that it can function.

Top of page

Writing the ActionScript code for the mp3 player

63 Call the current layer on the main scene player and lock it. Create a new layer an call it actions. Lock it too. You can enter ActionScript inside it whether it is locked or not.

Making a layer for ActionScript on the main scene.

64 Select the first keyframe of the actions layer by clicking on it. Hit F9 to open the Actions panel. Enter the following code inside:

var musicPlays:Boolean = false;
var loopTune:Sound = new Sound();
loopTune.onLoad = function(success:Boolean) {
if (success) {
loopTune.start(0, 999);
musicPlays = true;
_root.musicPlayer.gotoAndStop("playing");
}
};
loopTune.loadSound("cooltune.mp3", false);
musicPlayer.playStop.onPress = function ():Void {
if (musicPlays) {
this._parent.gotoAndStop("stopped");
loopTune.stop();
musicPlays = false;
} else {
this._parent.gotoAndStop("playing");
loopTune.start(0, 999);
musicPlays = true;
}
};

The music player won’t work just yet. You have to find an mp3 file that this player will load and play. Since this is a player that will play the mp3 tune only once it has been fully loaded (I will explain why later), you have to be careful when choosing an mp3 melody for it.

Top of page

Putting the mp3 file in the right folder

65 Find a mp3 looping melody. This file should be less then 100 KB in size, since it will be played only once it has loaded completely. If you’re making this player for a broadband Flash site, where you expect your users to be the ones with a really fast Internet connection, you can even choose a file that is bigger, up to 300 KB.

If you don’t have a good mp3 loop at hand, go check out my MP3 and WAV sites directory. You’ll find many links to websites that offer mp3 loops for download for free.

Once you have your mp3 loop music ready, do the follwing:

66 Place the mp3 loop file in the same folder where you saved the .FLA document you’re currently working on.

The mp3 loop file in the same folder as the Flash files.

67 Whatever the name of your mp3 file may be, rename it to cooltune.mp3 because that’s how you called it in the code that is placed inside your Flash document.

A little advice here: the best practice is to name your mp3 files in all lowercase letters (like cooltune.mp3 and not Cooltune.mp3). Because you might run into problems once you upload your files to a web server. It is easier to remember an all lowercase filename, and less likely to make an error when writing this name inside the ActionScript code.

Also, when you upload these files to your website, I recommend that you place all the three files in the same folder: the SWF Flash file that is going to be created from the document you’re working on right now, the HTML file that is going to have the SWF embedded inside it and finally, the MP3 file that is going to be loaded and played.

Do not upload the FLA file. FLA file is for you only and it doesn’t display on the web, in any browser whatsoever. Only the SWF file is intended for the web. If you need further information on this, check out my tutorial that explains the difference between FLA and SWF files.

You can place your mp3 in a different folder, but that requires some tweaking related to Flash security settings, which I’ll maybe discuss in some other tutorial. There’s still work to do here, I won’t be going off the topic :)

If something doesn’t work, check out with your hosting service if you’re allowed to place mp3 files on your web server. If they’re mp3 loops intended for Flash, and not commercial tunes, there shouldn’t be any problems with that. Also, ask them if there are any scripts or security settings running on the server that might interfere with the mp3 files from being used.

68 Test your movie (Ctrl+Enter). You should here music playing! :) Try clicking on the buttons to stop and restart the music. Also, when you pressed Ctrl+Enter and tested your movie, a SWF file was created right in the same folder where you saved your FLA file.

I will show you now how the ActionScript makes possible for the music player to play a mp3 tune in a loop.

Top of page

The ActionScript behind the mp3 background loop tune explained

The first line creates a variable, musicPlays, by which you tell Flash if the music is playing or not.

var musicPlays:Boolean = false;

This variable is of a Boolean type, as defined by the keyword of the same name. The value of a Boolean variable can be either true or false. If you wonder why is it called this way, it is because it was invented by George Boole, an inventor who set the bases for all modern computer arithmetic, even though computers didn’t exist in his time! If you want to know more about him, go to Wikipedia’s site and type in “Boole” in their search box.

So, since the music hasn’t loaded yet, you set this variable’s value to false. The next line,

var loopTune:Sound = new Sound();

creates a new Sound object. You create this object by creating a variable (named loopTune in this case) and writing new Sound() on the right side of the equals sign.

This object is used to load mp3 files into Flash and manipulate them. So once Flash has read this line, this object is created and stored in computer’s memory, where it waits and does nothing until you tell it to perform an action.

Now comes the onLoad function.

loopTune.onLoad = function(success:Boolean) {
if (success) {
loopTune.start(0, 999);
musicPlays = true;
_root.musicPlayer.gotoAndStop("playing");
}
};

This function is tied to your sound object (loopTune.onLoad) and has a parameter passed to it (success:Boolean). The success variable is of a Boolean type also, so it turns out either true or false.

Inside the function, there is a conditional if statement. The condition: (success). When you write only a variable name inside a conditional’s parentheses, it means only one thing: if this between the parentheses turns out to be true, execute the actions that come next. If not, skip them altogether as if they even don’t exist.

So this means that if success equals true (success is of Boolean type also), every ActionScript command between the curly braces ( { and } ) will be executed.

If success turns out to be false, nothing of this gets executed. And when does success turns out to be either true or false? Well, simple. If the mp3 file (cooltune.mp3) loads successfully, it turns out as true. If not, its value becomes false.

So, if everything is fine and the mp3 tune has loaded successfully, the conditional statement’s contents get executed. Let’s have a look at those.

loopTune.start(0, 999);
musicPlays = true;
_root.musicPlayer.gotoAndStop("playing");

The first line tells your loopTune sound object to start playing. The first parameter between the parentheses is the delay. It tells Flash if the loaded mp3 file should start from a certain point in time. It is set to zero, which means that it will start from the beginning. If you set it to 1 for example, the mp3 would start 1 second after its beginning.

The second parameter is the number of times this tune will loop (i.e. repeat itself). I put 999 because this means infinitely for all practical purposes. Say, for example, that your mp3 background tune has a duration of 30 seconds. This means that by putting the loop parameter to 999, it will be played for almost 30.000 seconds, which means 500 minutes. I doubt that anyone would stay at a single webpage or even a website that long. So you’re confident that the music won’t stop playing while someone is visiting yours or your client’s site.

The second line, musicPlays = true, tells Flash that music is playing now. This will come in handy later.

The third line tells the musicPlayer movie clip (the one you designed throughout this tutorial) to jump to the frame labelled playing and stop there. This frame is the one the equalizer is on. It makes sense – the music begins playing, and the equalizer stars to move happily. :)

Now comes the loadSound method. It tells the loopTune sound object to load the mp3 file called cooltune.mp3.

loopTune.loadSound("cooltune.mp3", false);

The second parameter between the parentheses tells Flash if this mp3 sound is a streaming one (meaning that it will begin playing as soon as a portion of it has loaded and will continue playing while it is being loaded at the same time) or not.

Here, it is put to false. This means the sound won’t begin playing until it has fully been loaded. This is made so because the previous function, onLoad, does not work and cannot work if this value is set to true. That’s why I told you to find a background tune that has to be small in filesize. You wouldn’t want to put an mp3 tune that has a size of 2 megabytes here and have to wait until that loads! That makes no sense.

And the last part of ActionScript is the one that makes the button for controlling the playback work.

musicPlayer.playStop.onPress = function ():Void {
if (musicPlays) {
this._parent.gotoAndStop("stopped");
loopTune.stop();
musicPlays = false;
} else {
this._parent.gotoAndStop("playing");
loopTune.start(0, 999);
musicPlays = true;
}
};

The musicPlayer.playStop construction is the target path to your button. Since it is inside the musicPlayer movie clip, you have to target it by writing musicPlayer.playStop.

Then you assign an onPress event to it. This event happens when a user clicks the button in question. A function is tied to it. This means that when a user presses her mouse button over this button, this function will be executed. The Void keyword means that this function does not return a value. It simply does a few things.

Inside the function, there is a conditional if / else statement. It says that if the value of the musicPlays variable equals true (musicPlays), the button’s parent movie clip (the one inside whom the button is situated – musicPlayer), jumps to frame labelled stopped and stays there.

if (musicPlays) {
this._parent.gotoAndStop("stopped");

This too makes perfect sense. A user clicks the button, and if the music is playing (musicPlays is true) the movie clip goes to frame with the label stopped where the equalizer isn’t present. This is good, because you don’t want it to jump around if there is no sound to be heard.

After that, the mp3 sound is stopped with the line

loopTune.stop();

and the value of the musicPlays variable is set to false, because the music isn’t playing any more.

musicPlays = false;

So, the user has turned the music off. Suppose it wants it to play again (play it again, Sam). She clicks again. Remember, the value of the musicPlays variable has just been set to false.

The conditional if statement sees this and skips the first pair of curly braces – { and } and proceeds to the else part. The else part gets executed.

} else {
this._parent.gotoAndStop("playing");
loopTune.start(0, 999);
musicPlays = true;
}

Inside it, the musicPlayer movie clip is told to jump to the frame where the equalizer is visible (the frame called playing), the sound is being turned on again (loopTune.start), with the same parameters as before and the value of the musicPlays variable is set to true because the music is playing.

Simple, isn’t it? To translate this into english:

if (the music is playing) {
- hide the equalizer
- stop the music from playing
- set the musicPlays variable to false
} else {
- show the equalizer
- start the music
- set the musicPlays variable to true
}

Cool! Conditional statements are very useful, and yet simple to implement as you can see!

Top of page

Placing the mp3 player inside a HTML page

To place your mp3 player into an HTML page, you have to make your document’s dimensions smaller first. The dimensions of the player I made are 41 by 54 pixels. Yours may be smaller or bigger, depending on the size of the player’s background rectangle. So, do the following:

1 Unlock the layer with the player. Click on the mp3 player movie clip to select it.

2 Open the Align panel (Window > Align). Make sure that the Align to Stage button is turned on (see 1 on the image below). Click on the Align top edge button (2) and then on the Align left edge button (3).

Aligning a movie clip in relation to the stage.

Your movie clip will now be sitting perfectly in the top left corner of the stage.

3 Move the movie clip with the arrow keys on your keyboard 1 pixel to the right and one pixel down.

4 Go to the Properties panel and look at the dimensions of your movie clip. Mine are 41 by 54 pixels (the dimensions are found in the W and H fields). Remember them or write them down.

5 Open the Document properties window (Modify > Document). Make the size of your document 3 pixels bigger than the dimensions of your movie clip, both the height and the width.

The width of my movie clip was 44 pixels, so I put the width of the document to 44 pixels. Likewise, the height was at 54 pixels, so the document’s height I set to 57 pixels.

Click OK. You will have a fine small SWF file now, with a 1 pixel border around the mp3 player movie clip.

So, to put this gizmo into an HTML page, just place the SWF file (in Dreamweaver or whichever webpage building program you might be using) into a cell of a table on your page, or a layer if you’re working with CSS. Put it somewhere on top of your page, near the header, navigation, etc, so that it is easiyl visible and accessible.

Top of page

Placing the mp3 player inside a Flash site

If you are placing your mp3 player into a Flash site, which consists of a SWF file, of course, just pay attention to the following:

  • Make sure that the music player movie clip is placed on a separate layer, not to interfere with other content,
  • That this layer isn’t covered by some other elements of your main Flash site movie,
  • Be sure to check that there aren’t any variable name conflicts. For example, if you have a button that is called playStop both in your mp3 player and on your main site, this is not good – you will certainly lose some, if not all of your movie’s functionality.
  • Place the ActionScript for the player on a same level of timeline where the player is.

That’s not an exhaustive list, but it will give you some good directions to consider when placing your mp3 music player movie clip inside an existing FLA file.

If you want to change the way your player looks, it is easy. Just change the color gradient bar graphic symbol (double-click on it inside the Library to change it), the color and look of the background rectangle, the play and stop icons, and you’re done. You can even rotate the equalizers. Just look at the cool results you can obtain:

I hope that you had fun learning from this tutorial as much as I had creating it. Ride on!

Download the zipped source FLA file for this lesson.

Download the source file for the second mp3 player.

Be Sociable, Share!

Comments

Submit a comment

  • Puneet Oct 23, 2008 at 8:44 am

    Awesome tutorial… It sure did help..
    well, I wanted to make a mp3 player for my music site, in which I could update the song list… It should have a playlist, visualization, volume control, and all the basic features(skip fwd, skip bkwd, etc.).. and one thing that I couldn’t find on any online tutorial was to make a draggable controller(to goto any point of the song)..
    I know this is too much to ask for, but I would really like to learn to create something like a SoundClick Widget.. :D
    The major problem is that I don’t know XML :(

    But this tutorial helped me develop the basic player.. Thanx a Lot

  • Luka Oct 23, 2008 at 9:30 am

    Puneet, maybe I will make a tutorial about an mp3 player in the future. As for XML, see the Hangman game tutorial, it’s all explained there.

  • Puneet Oct 28, 2008 at 7:44 pm

    Luka, I got the basic idea about XML. I made a XML driven mp3 player for my site with play/pause toggle, next song, previous song, mute controls. And I used the visualisation I learnt from here :D
    But I would be very thankful to you if you could give me a basic idea for making the seek-bar, so that the user can drag it to any position..
    Thanx a lot :)

  • Luka Oct 28, 2008 at 8:33 pm

    Puneet: I will when I’ll find the time. I’m way too busy at the moment. Glad to hear you’re making progress. Congrats!

  • Jerry Peterson Nov 2, 2008 at 2:59 am

    Dear Sir ,Your players are just what I was looking for. Small and beautiful. Thank you and I also learned a lot about Flash by your tutorial. Can you advise where I can get the mp3 music file you use on the player at the top of the page. I dont know if this is “cooltune.mp3″ or not but is is nice and mellow and that is all I want. For my site I dont want loud, obnoxious music starting up when the user enters the site but something like the music you have in your example. Thank you very much Jerry

  • Luka Nov 2, 2008 at 11:12 am

    Jerry Check out my mp3 and WAV resources for loop downloads. You may also try platinum loops for quality commercial loops.

  • Rod Nov 2, 2008 at 9:22 pm

    Great job, Luka!!!! I’m a beginner, trying to learn more things… most flash jobs, I just kind of decompile existing flash files and recompile them using different images when possible. Thanks so much for the fantastic tutorial. I use MX Pro 2004 so I could NOT use your FLA file (neither can I use any of your FLAs for Flash 8 good stuff), but was able to follow your instructions step by step. However, I defaulted when trying to configure the 4th bar… I am also testing the other option, which you can see at: http://www.kurlandvodkaimports.com/intro.htm – the MP3 is a bit heavy, but thats all I had at hand and this site needed some fun music to go along the intro. Thanks again and I will appreciate any feedback! I’ve bookmarked your site.
    Best regards,
    Rod

  • Luka Nov 3, 2008 at 8:45 am

    Rod: Nice site. I would however cut the intro time a bit. The “skip intro” option is fine, but maybe it should be a little bit shorter anyway. Keep up the good work!

  • Yonaston Nov 30, 2008 at 2:52 pm

    Everything works fine until i try to play the loop music. Then i get this error:
    Error opening URL “file:///C|/Documents%20and%20Settings/susan%20green/Desktop/mp3%5Fplayer/looptune.mp3″

    I’ve tried numerous different mp3 loops and it keeps happening? Please help!

    Ian

  • Jasper Dec 12, 2008 at 10:16 am

    Hi Luka,
    Fantastic tutorial. I have a quick question as well: how do you import the mp3 player inside a Flash site, which as several scenes? Doesn’t moving between scenes in the Flash site stop or interrupt the music?
    Cheers!

  • Chaz Curry Dec 23, 2008 at 5:06 am

    Great tutorial!!!

    Question:

    When I make the mp3 stream and start playing right away, the eq is still frozen as if it isn’t playing and when the mp3 finally completing loads it resets the mp3 back to the beginning.

    Any ideas?

    Thanks so much!

    - Chaz

  • Nickson Jan 4, 2009 at 12:53 pm

    You have a very useful tutorial… and you even share your .FLA file!
    You might need to add a feature, no auto play onLoad:
    Original code:

    var musicPlays:Boolean = false;
    var loopTune:Sound = new Sound();
    loopTune.onLoad = function(success:Boolean) {
    if (success) {
    loopTune.start(0, 999);
    musicPlays = true;
    _root.musicPlayer.gotoAndStop(“playing”);
    }
    };
    loopTune.loadSound(“cooltune.mp3″, false);
    musicPlayer.playStop.onPress = function ():Void {
    if (musicPlays) {
    this._parent.gotoAndStop(“stopped”);
    loopTune.stop();
    musicPlays = false;
    } else {
    this._parent.gotoAndStop(“playing”);
    loopTune.start(0, 999);
    musicPlays = true;
    }
    };

    No auto play onLoad code:

    var musicPlays:Boolean = false;
    var loopTune:Sound = new Sound();
    loopTune.onLoad = function(success:Boolean) {
    };
    loopTune.loadSound(“cooltune.mp3″, false);
    musicPlayer.playStop.onPress = function ():Void {
    if (musicPlays) {
    this._parent.gotoAndStop(“stopped”);
    loopTune.stop();
    musicPlays = false;
    } else {
    this._parent.gotoAndStop(“playing”);
    loopTune.start(0, 999);
    musicPlays = true;
    }
    };

    I don’t really have Action Script coding experience but I have HTML and a little JS coding experience…

  • Steve S Jan 18, 2009 at 9:48 pm

    Great Tutorial,

    Im building a site with multiple pages (scenes), and have added the mp3 player to the pages, however everyttime you click one of the buttons to go to the next scene the mp3 file obviously reloads and starts from the beginning.

    Is there a simple fix to this, i.e. having the player present on all pages and it playing continously regardless of what page/scene its on?

    Thanks

  • M.benbaziz Jan 22, 2009 at 11:00 am

    great tutorial, thanks for sharing with us all.
    I don’t know why when I preview the player, the music loads and plays but the equalizer doesn’t show and the buttons don’t make any change, I double checked everything and it seems in order, any tip of where the problem might be?
    the music player movie clip is not jumping to the frames (playing) and (stopped).
    I appreciate your help.

  • Diego Mar 2, 2009 at 6:44 am

    Hi, hope you’re having a good time, great tutorials. I’m using flash 8, and i’m trying to make a Piano, and i have some trouble. Hope u can help me… If you have ever played a piano, you know that the sound keeps playing while you hold the key, and after a while, it fade away. And, when you strike a note, and release it, the sound stops.
    - How can i get that effect using actionscript? I did it, but using a mouse, so, How to do it, but using the keyboard?
    - And other, not related with sound… sorry, but, Is it possible to make buttons work the same way with the keyboard as they do with the mouse?
    i mean, with an usual button, for example, you pass the mouse over, it change color, you click and change… How can i get that effect, but with the keyboard?.
    Hope u can helo me… and thanks again for your great tutorials.

  • Mahmut Apr 23, 2009 at 1:29 pm

    Hey Luka ive learntt sooooo much from this site your simply the best your way better then my teacher haha! matey got one question atm im in progress of making a website ive got a group on facebook its a music group got over 14k peolpe waiting for a website from me im kinda stressing out alot ive finished all my pages on my website but im stuck on ‘Gallery’ and ‘Music’ pages I want to create a flash ‘Gallery’ and a ‘Music player’ with a ‘playlist’ ive searchh soo many places but just cant get a answer to it and as i stated before my teacher isnt the best at her job so shes clueless so im stuck and i need your help! if you can e-mail me on mahmutgedikoglu@hotmail.com or even add me on MSN would be APPPRICATED because im stuck and i seriously dont know what to do please Luka all the best dude.

  • SEspider May 5, 2009 at 12:47 am

    I don’t know what I did wrong.
    I followed the directions to the letter but the music plays at the start (for now that’s what I wanted), but the buttons don’t work and the equalizers don’t show up.

    Please help. thanks

  • splashmilk Jul 15, 2009 at 2:17 am

    Hello. Your tutorial is wonderful, i am new to flash but ur tutorial is very informative and easy to understand. But i also have some extra function that i would like to add to the mp3 player but i dunno how.

    1. May i ask how to include a “PAUSE” button with the “PLAY” button when u hover on it?

    2. How to “fade out” the music when “PAUSE” button or “STOP” button is clicked and “fade in” again once “PLAY” button is clicked?

    I would be very grateful if you can help. Thanks!

  • Sanjay Malhotra Aug 13, 2009 at 5:49 pm

    I’m getting this error:

    Scene=Scene 1, Layer=actions, Frame=1: Line 11: ‘{‘ expected
    musicPlayer.playStop.onPress = function ():void {

    Scene=Scene 1, Layer=actions, Frame=1: Line 21: Unexpected ‘}’ encountered
    };

    Please suggest what error I’m doing:
    :-)

  • azdark Sep 20, 2009 at 9:31 pm

    great tutorial!!!!

    if u find time pls make a vid it would be easiier to follow up!

  • LuCk Oct 13, 2009 at 12:25 pm

    Good Tutorial, dude!

  • JMB Feb 8, 2010 at 10:21 pm

    AWESOME!! THANKS!! BUT ONE QUESTION IF YOU READ THIS!! (please)

    How can I add more than one track for it to play through and will this increase load time? THANKS!!

    THIS WAS JUST WHAT IVE BEEN LOOKING FOR!!!!

  • Sasa Feb 12, 2010 at 11:13 pm

    One little thing.. equalizer is used to filter sound and visualizer is used to display sound volume in different freq..

    Anyway, tutorial is perfect ! GREAT WORK!!!

  • ziinine Mar 19, 2010 at 9:44 am

    hi

    hi my name is ziinine i live in Malaysia .i m a graduate in Multimedia .I liked your Making a simple player for mp3 loops with a visual equalizer,but can u please tell me or give me the actionscript or a technique that can make your radio mp3 player plays many songs continuously,instead of only one looping song ?

  • Phoebe Mar 23, 2010 at 5:35 am

    this is really great!

    Thanks for this useful tutorial, it really works for me as I follow the steps.

    And thank Nicson’s providing the “no auto play onLoad code”, that’s exactly what I just need in the last step!

    Here I’m stuck in one other step. My mp3Player’s background layer’s object is a “movie clip”, it starts to act right at the moment the swf file loads. I want the movie clip not to start acting till the button was clicked.
    How can I do? I wrote a “stop();” code, in the first fram of the actions layer, but it doesn’t work though.

    Anyone who can give me some advice? Thanks a lot.

  • elle May 29, 2010 at 7:52 pm

    I am getting this error
    Scene=Scene 1, Layer=actions, Frame=1: Line 11: ‘{‘ expected
    musicPlayer.playStop.onPress = function ():void {

    Scene=Scene 1, Layer=actions, Frame=1: Line 21: Unexpected ‘}’ encountered
    };

    How will I debug it

  • ben cyster Jun 3, 2010 at 7:47 pm

    how do you think you will get the best sound from this i make flash players all the time and all of mine are alot intence to use so please email me and i mite be of some help to you.thank you all i hope to here frome you soon:)

  • Pasquale Jun 5, 2010 at 3:49 pm

    Hey, thanks so much for the tutorial. I’m glad you posted the flash file itself or I wouldn’t have known where I put the action script wrong. AND that it works in flash 8!!

    :D

  • rz Nov 21, 2010 at 7:10 pm

    Test

  • Blair Booth Mar 30, 2011 at 7:03 pm

    Many thanks for the tutorial. How would i go about putting more than one of your player’s on my flash page? How would I script this?
    Thanks
    Blair

  • Jarred Michael Mar 21, 2012 at 12:22 am

    URGENT: I use iWeb and a Mac. How would I do this for Mac?

  • arif Jun 26, 2013 at 3:38 pm

    its not playing my music when i upload in server can u tell me ? how it will play on server

Leave a comment