Web Hosting
GigFoot Web Hosting


FAQ Index / Top Ten FAQ's / Newest FAQ's / Search / Go Back

How do i make a Streaming MP3 Player in Flash?

We have a ready-built mp3 player with everything you need to run your own mp3 player. See our software page for a working demo and more information.

Streaming MP3 music into Flash is built into Flash Player 6. You can call MP3 files directly into your Flash world and control several sound properties. This sample utilizes these techniques by constructing an MP3 Player. A Flash file is passed an mp3 url and the movie clip streams the mp3 from the url. We can pause the sound, skip ahead, and adjust volume and panning. With Action Script, we’ll be loading a sound object onto the stage, telling the sound object what url to play, and tracking the sound objects position and duration. A complete working Flash example file can be found at MP3Player.fla. For portability, we’ll keep the mp3 player in it’s own movie clip. This way we can add drag controls and be able to call our MP3 player into other projects down the road.

The heart of this project is the sound object. Every object in Flash has properties, events and methods unique to the object. The sound object has several we can work with.
Sound.attachSoundAttaches the sound specified in the parameter.
Sound.getBytesLoadedReturns the number of bytes loaded for the specified sound.
Sound.getBytesTotalReturns the size of the sound in bytes.
Sound.getPanReturns the value of the previous setPan call.
Sound.getTransform Returns the value of the previous setTransform call.
Sound.getVolumeReturns the value of the previous setVolume call.
Sound.loadSoundLoads an MP3 file into the Flash Player.
Sound.setPanSets the left/right balance of the sound.
Sound.setTransform Sets the amount of each channel, left and right, to be played in each speaker.
Sound.setVolumeSets the volume level for a sound.
Sound.startStarts playing a sound from the beginning or, optionally, from an offset point set in the parameter.
Sound.stopStops the specified sound or all sounds currently playing.
* From the Flash MX Action Scripting Guide. Flash Sound Properties*
Sound.durationLength of a sound in milliseconds.
Sound.positionNumber of milliseconds the sound has been playing.
* From the Flash MX Action Scripting Guide. Flash Sound Event Handlers*
Sound.onLoadInvoked when a sound loads.
Sound.onSoundCompleteInvoked when a sound stops playing.
* From the Flash MX Action Scripting Guide.

Since we want to stream an mp3 file, we will use the loadSound Method. Make a new Flash file and call it mp3player.fla. This sample requires an mp3 file. You will need the url of this mp3 file in order for this sample to work. A url can be a local address on your computer or an internet web address. Here’s the action script needed to load an mp3 file. Place this code in Frame one (Action’s panel).

s = new Sound();

In the code above we create a new sound called “s”. We then load a streaming sound into our “s” by passing it the url to our mp3 file. The second parameter of loadSound we set to “true.” This tells Flash “s” is a streaming sound. Streaming sounds play as they load into Flash. You can use a local address or an http address. Over a web connection, a 3-minute mp3 file will start almost immediately. Run this example in Flash and you will hear your mp3 file playing. If not, double-check the url of your mp3 file in a browser address bar. Also keep your mp3 file names simple for this exercise; avoid long names, spaces and other non-letter characters in your url. It will make debugging much easier.

Add Play and Pause Buttons to MP3 Player

We will add a pause and play button to our MP3 player. So far our mp3player.fla stage is empty. There’s only two lines of action script in Frame one. We have our MP3 file available and know the url to locate it. Draw a graphic to your liking resembling a play button. Convert the graphic to a button by highlighting the graphic and selecting “Convert to Symbol”(key F8). Name your new button “PlayButton” so you can recognize it by name in your library. Customize your Play button graphically for up, over, and down styles. Now add the following action script to the button you just made. Select the button from the main stage and in the Actions panel add the following code.


This code tells our sound we named “s” in frame one to start playing at cue. When you click the button, the mp3 file will begin playing at the value of cue. We will set the value of “cue” when the user clicks the pause button. This will allow the sound to stop and start again from where it left off. Add your pause button along side your play button. Create it from scratch just like you created your play button. Name your pause button symbol “PauseButton” so you can recognize it by name in your library. Another popular shortcut is to duplicate your play button on the stage and click the “Swap Symbols” button in the Properties palette. In the Swap Symbol window, click the Duplicate Symbol button. Name the duplicate PlayButton “PauseButton” and hit OK. Then double-click the new “PauseButton” Symbol in the Swap Symbols list. This will assign your new button to the symbol named “PauseButton”. The active symbol is designated by a bullet. Now you have two play buttons on your main stage, one is called PauseButton. Edit this button graphically to resemble a pause button. Then edit the action script in the Actions panel. Highlight the pause button on the main stage and place the following action script into the Action’s code panel. This code should replace any play button code if you duplicated the PlayButton symbol.

cue = Math.round(s.position/1000);

Here we set the value of our variable named cue to the current position in the sound file. The position is the number of milliseconds the sound file has played. Since our sound start method requires seconds, not milliseconds, we divide the position value by 1000. After we set the cue variable we stop the sound. When you click the pause button, cue gets a new value and any sounds stop playing. When you click the play button the sound begins to play at the number of seconds designated by our variable cue. Publish and test your mp3player movie. It will begin playing the mp3 file as soon as you run it in the browser. When you press the pause button, the music stops. When you press Play, the sound begins playing where it last stopped.

LocationAction ScriptDescription
Level_0 (main stage)s = new Sound();s.loadSound("C:/myMusic/song.mp3",true);Creates the streaming sound and plays the mp3 file
PlayButtonon(release){s.start(cue);}Plays the sound starting at position cue
PauseButtonon(release){cue = Math.round(s.position/1000);s.stop();}Sets cue to the number of seconds elapsed into the mp3 file and stops the sound.

SIDEBAR! Caution, at the writing of this book, there was a bug in some Flash player plug-ins effecting sound streaming stopping and starting. If you are not using the most current version of Flash MX, there may be a patch available. See url http://www.macromedia.com/support/flash/ts/documents/flashplayer_r40.htm for futher information. For the author, the play button only worked through a web browser. Publish the HTML version of your Flash file. Run the most recent flash player to test your flash file. Or upload the swf file to a web server and run it in a web browser. Macromedia has fixed this bug. Insert fg1601.tif Figure 16-01: Pause and Play Buttons. So far, we’ve built a working mp3 player with two buttons on the stage. Add Title and Time display to MP3 Player (optional)

If you are anxious to get the FCS song sharing application you can skip the next three samples. They are included as added features to the MP3 player. They are not necessary for the nightclub to run properly. Above your pause and play buttons add a text box. Make it a dynamic text box and assign the variable name “title”. Make the text box wide, you know how long MP3 file names can be. In the title box, we will display the mp3 title and the length of the track playing. We will also use the title box to inform the user of sound status changes.

We will be updating the title from several places in our MP3 Player. Let’s start with the sound load event. When the MP3 file has been loaded into the sound object “s”. Flash fires an event called onLoad. We can listen for this event and do something when it happens. In Frame one of the main stage add the action script below.

s = new Sound();
src = "C:/myMusic/song.mp3";
s.onLoad = function(){
title = "Song Had Loaded";
s.onSoundComplete = function(){
title = “Song complete”;

When the sound loads into object “s”, we update the title box with a message. Flash also fires an onSoundComplete event when the sound is finished playing. We listen for it also and update the title with a completed message. Publish and run your mp3 player now to make sure you set your dynamic title text box up properly. When you run the published file you should see the title box read, “Song has Loaded” every time you click the play button. If not double-check your title box. Does the variable field say “title” in the properties window? Is it a dynamic text box? To take our mp3 player to the next level we’ll need to extend our timeline a bit. In order to update a time clock to display the song counter we’ll need a loop. In the loop we can update the title box with our current cue position in the song. We can convert the cue value of total seconds to a friendly minutes and seconds format. This value will serve as a player clock. Since we have pause and play buttons and we need a loop, let’s use frame labels to refer to different positions in the timeline we can go to depending on the song status. If the song is playing we will send the movie to label “Playing”, if the song is paused, we will go to the label “Paused”. In the main stage timeline of mp3player.fla create a new layer and call it labels. Keep this layer empty. Only use it for label names. This is a good habit to get into for organization purposes. This layer will hold all the labels we need in our file. In Frame number 10 insert a blank keyframe in the labels layer. Highlight the frame in the timeline and in the Properties panel set the frame’s label value to “Playing”. Do this again at frame number 20 on the labels layer. Insert a blank keyframe at frame 20 and name it “Paused”. Insert a regular frame (a non-keyframe) at frame 30. Now we can refer to frame 20 as Paused and frame 10 as Playing.

In your timeline, rename the original layer containing your buttons and title box. Change the layer name from Layer 1 to “controls”. In the timeline, place a regular frame (a non-keyframe) at frame 30 of the controls layer. In addition, create a brand new layer. Name this layer “actions”. Just like labels, keep the actions layer empty. Use it only for action script. This is a very good habit to get into, especially if you collaborate with others. Move the action script we put in frame one of what is now the controls layer into the actions layer. Now we have three layers on our main stage, labels, actions, and controls. Our timeline is 30 frames long. We have a play and pause button as well as a title box. When the song is playing we want to send the movie to frame 10 labeled Playing. At label Playing, we want the movie to loop until the song stops playing. In this loop we can update the title with the current time in the song. If the song stops for any reason we want to send the movie to the Paused label.

First let’s make the loop complete at our Playing label. In the actions layer, at frame 12, place the following code. gotoAndPlay(“Playing”); Now let’s edit our Playing label. This is the loop start point. At frame 10, in the actions label, place the following action script.

title = s.position+” of “+s.duration+" "+src;

This will update the title box with the current sound position in milliseconds. The sound position value is the current elapsed time in milliseconds of the mp3 file. The duration is the entire length of the current stream in milliseconds. We are relying on Flash’s onLoad event to send us to the Playing loop. We tell Flash to gotoAndPlay(“Playing”) in Frame 1 of our actions layer. Now we have a self-updating clock displayed in our title box. Run and test your flash movie and you will see the title box update the sound position in milliseconds. Hit the Pause button and the song stops.

Add a Seek Bar to our MP3 Player

What do you get when you combine a cue variable with the time clock? The answer is a fully functional seek bar in Flash. In this example we will extend our MP3 player further to allow the listener to seek and play to a specific time position within the mp3 file. We will create a loading bar to graphically display the elapsed time and add a dragable slider to set the cue position of our song. The horizontal movement of the slider will correspond to the starting position in the mp3 file.

Slider bars

In the controls label where your buttons reside draw a horizontal rectangle. Make the rectangle 100 pixels wide and 20 pixels high. Convert this rectangle into a movie clip symbol (F8 key). Call this symbol “duration” so you can recognize it by name in the library. Highlight the duration clip and name the instance “duration” in the properties panel. Create a new rectangle using a different color. Make it the same height and width as duration. Convert it to a movie symbol called “position” (F8 key). Highlight position and edit the instance name from the properties panel. Change the instance name to “position”. Make sure position is a different color than duration. Both clips should be overlapping. Make sure the position clip is on top of the duration clip. Also move the zero point to the top left corner in both clips. Double-click position. You are now editing the raw graphic rectangle by itself. Select the rectangle and change it’s X and Y to 0 in the properties panel. Do this step for both the duration and position clips. We can now link the sound’s position property to the width of the position bar and the duration property to the duration bar. We will link these items in the Playing loop so the bars will dynamically change as the song progresses. In the actions layer of the main stage, edit frame 20 (label Playing).

duration._width = s.duration/1000;
position._width = s.position/1000;

We are dividing by 1000 to save our movie clip from getting too wide.

Since we want this to play many different sizes of MP3’s we will want to constrain our loading bar’s width in the mp3 player window. The loading bar’s effect will remain intact but the overall width will be constant. To do this select both bars on the main stage and convert them to a movie clip symbol (F8 key). In the properties panel, name the symbol instance cuebar. Now duration and position are no longer on the main stage. They are now found inside of playbar. The clip playbar is found on the main stage. In the actions layer of frame 20, change the action script to the following.

title = s.position+" of "+s.duration+" "+src;
playbar.duration._width = s.duration/1000;
playbar.position._width = s.position/1000;
playbar._width = 100;

Publish and run your mp3 player now. You should see the title box report the current position and duration of the sound. The playbar’s position will grow in width as the song plays. Your Main Stage should look something like figure 16-02. In the figure I made the position bar green and the duration bar dark green. I made position shorter so you could see the color contrast. Notice how position needs to be in front of duration. The white box above the playbar is the title bar. I set the show border and box preference in the properties panel. When you run this movie the title box will be updated in the Playing loop. Insert fg1602.tif Figure 16-02: Main Stage of our MP3 Player.

Add a dragable button to the seek bar.

Now we want the listener to be able to jump to a certain position in the song and start playing from that position. We will use our play bar as a backdrop for a dynamic drag button we will construct. We will update the buttons position to mimic the position bar’s width. Then we will start a drag event. When a user drags the button to another spot in the playbar, we will send the value to the sound. If the button is dragged to the beginning, the song will play from the beginning.

Make the Button

Create a graphic to represent a drag button. A good start is a vertical rectangle. 1 pixel wide by 25 pixels high. Convert this rectangle into a button symbol. Name the button dragger so you can recognize it in the library. Name the instance name of this button “dragger” also. Do this by highlighting the button and opening the preoperties panel. In the Playing frame loop, edit the actions label action script. Highlight frame 20 and open the Actions pallette. We’re adding one line to our existing code. The entire action script should now read.

title = s.position+" of "+s.duration+" "+src;
playbar._width = 300;
playbar.duration._width = (playbar._width*1);
playbar.position._width = ((s.position*playbar._width)/s.duration);
dragger._x = (s.position* playbar._width)/s.duration+playbar._x;

This script keeps the dragger’s x position in time with the music. As the sound plays, the dragger moves from left to right across the playbar. We had to compensate for the restricted width we placed on our playbar. If you change the width of playbar later, the dragger will still stop and the very right of the playbar like we want it to. In our example we set the overall width of the playbar to 300 but any value will work the same. Now the drag button moves with the music but it still doesn’t drag yet. Let’s add that feature now. Select the dragger button from the main stage. In the actions panel add the following action script to the dragger button.

cue = (((dragger._x-playbar._x)*s.duration)/playbar._width)/1000;

This confines our dragable area horizontally from the beginning to the end of the playbar. Again ,the playbar can be any size specified in the Playing frame. In the on release code we take the x position of the dragger and translate it into a second count. This will be our new start point in the MP3 file. We called this variable cue in frame one of our actions layer so we continue the tradition here. When you publish and test your Flash file, you can now drag the dragger button within the playbar. When you let go of the dragger the sound will start playing at that point in the song. You now have a fully function seek bar and time counter in your mp3 player.

Add a Volume slider control to the MP3 player.

Create the volume control slider and button

Let’s add a similar slider control to control the sound volume. We’ll use our Playing loop to keep the mp3 player updated with the current volume level. We can read this property directly from our sound object. It returns a value for volume from 0 – 100. 100 is the maximum volume. On the main stage in the controls layer draw another horizontal box similar to the duration bar. 100 pixels wide by 10 pixels tall is a good dimension. This will represent the entire volumn range. Convert this rectangle to a Movie Clip symbol called volSlider. Name the new symbol’s instance name volSlider. Double-click the volSlider clip. You are now inside volSlider symbol. Set your rectangle’s x and y to zero on the stage. Make a dragger button here. 5 pixels wide by 10 pixels tall is a good dimension. Convert this rectangle into a button (F8 key). Set the button instance name in the properties panel. Set the name to dragger. You can also just duplicate the main stage dragger here inside of volSlider. Make sure you Swap names if you do. And edit the action script described next.

Code the Volume control dragger button

Edit the Actions panel of the dragger button found inside of volSlider. The code should read as follows:

isDrag = "y";
isDrag = "";

We you release the button, the sound’s volume property is set to the x position of dragger. We also want to keep the dragger button in the current position of the sound volume. We can retrieve the volume property in the Playing loop on the main stage. This loop will allow us to update the volSlider dragger button should the volume level change. Back on the main stage, add the following action script to the Playing actions frame 20. We added one if statement to the bottom of what we already covered. Now our action script updates the volume button thanks to the sound object’s getVolume() property. Below is the entire action script for frame 20 inside the actions layer. Update Volume in the Playing loop

title = s.position+" of "+s.duration+" "+src;
playbar._width = 200;
playbar.duration._width = (playbar._width*1);
playbar.position._width = ((s.position*playbar._width)/s.duration);
dragger._x = (s.position* playbar._width)/s.duration+playbar._x;
if (volSlider.isDrag eq “”){
volSlider.dragger._x = s.getVolume();

One final touch we added was to only update the volume slider in the Playing loop when we are not dragging. That’s why we set isDrag to “y” on press and emptied it on release in the VolSlider dragger button. The Playing loop will now only update the slider when we are not sliding it. Skipping this step causes unpredictable sliding results. Run and test your Flash file. Since the default volume for Flash sounds is 100. The volume slider will immediately slide to maximum 100 when the sound first loads. You can adjust the volume to 0 and you will not hear the sound playing.

Add a Pan Slider control to our MP3 Player

Create the pan control slider and button

In addition to adjusting the volume, we can also change the left to right speaker pan value. We can play more of the sound in the left channel or more into the right. Let’s add a pan slider that works just like volume. Dragging the pan button to the left will play the sound in the left channel. To the right will pan to the right speakers. Duplicate the volume slider you made in the example above. Swap the symbol names so we can customize it as a pan symbol and not a volume symbol. Highlight the volume button. Duplicate the symbol on the main stage. Select the duplicate and press the Swap button in the properties panel. In the Swap Symbols dialog window click the Duplicate Symbol button. Name the new symbol panSlider instead of volSlider Copy. Double click the new panSlider symbol to apply the change to the active clip. Click OK to apply the settings. Change the instance name of our new slider to panSlider. Do this in the properties panel after highlighting the symbol. You should now have a volume slider and a pan slider on the main stage. The volume control is called volSlider and the pan is called panSlider. Let’s edit the buttons action script to change the sound objects pan values.

Coding the pan control slide button

Double-click panSlider so we can edit the dragger button inside. We don’t set pan the same way as we set volume. Highlight the dragger button inside of your panSlider movie clip. Change the action script to the following:

isDrag = “y”;
isDrag = “”;
v = dragger._x*2;
if (v <= 100){
v = v + -100;
v = v - 100;

Pan values are from –100 to 100. That’s a range of 200, which is why we multiplied our x position by 2 on release. If the x position times 2 is less than 100 we send a negative number between –1 and –100. If it’s greater than 100 we send a positive number to the sound pan ranging from 1 to 100. Either extreme of the slider will produce a pan in either the left or the right speaker accordingly. It’s a relational value based off the integer you pass to the sound’s setPan method. Run the code to see how it works. As the sound is playing you can adjust the pan property dynamically.

Update pan in the Playing loop

Now we need to update the pan button in our Playing loop. If the pan property gets changed from outside our panSlider we would still want the pan Slider to reflect the current pan value. Let’s add this updater now to the main stage. In frame 20 (label Playing) add the following action script to the actions layer.

title = s.position+" of "+s.duration+" "+src;
playbar._width = 200;
playbar.duration._width = (playbar._width*1);
playbar.position._width = ((s.position*playbar._width)/s.duration);
dragger._x = (s.position* playbar._width)/s.duration+playbar._x;
if (volSlider.isDrag eq ""){
volSlider.dragger._x = s.getVolume();
if (panSlider.isDrag eq ""){
panSlider.dragger._x = (100+s.getPan())/2;

You have now completed the pan slider and the volume slider for the mp3 player. Both sliders are updated by the sound properties methods inside of the Playing loop on the main stage. In addition you have a working seek bar and our play and pause buttons. Pretty much all of our basics are covered. There’s still more tricks you can add. A transform slider would allow you to set and retrieve 4 additional channel mixing values. Slight distortion of sound is possible with this transform method. Its still mixing from channel to channel but you can overload certain channels for some unexpected effects.

Using the MP3 Player

At this point, there are tons of options open to you with your MP3 Player. Since the article is about FCS, we’ll focus mainly on shared tricks between multiple users. But the MP3 Player as it stands now is very expandable. You could pass the src value of the mp3 url you want to play instead of calling declaring it statically in frame one. Then an html source page could load the swf object with a different mp3 playing based of a user’s choice from a list. Or the Flash file itself could read in a playlist from a text file declared in a loadVariables statement. Then more controls could be added to allow the user to choose which songs to play. Or a looping playlist could be editable by the user. The possibilities are endless.

Prev Question / Next Question / Question Index
What do you think of this Question? Vote Thumbs Up or Thumbs Down. Vote Toes Up for this Item Vote Toes Down for this Item Reputation: 3 / Feedback: 0