Tuesday, 22 September 2009

action script for creating a mp3 player (action script 3)

How To Code A Full Functional MP3 Player Using ActionScript 3.0







create a new flash file (action script 3) type the following code.

var track:Sound = new Sound;

var index:Number = 0;

var trackPos:Number = 0;

var trackOn:Boolean = false;

var trackXML:XML;

var trackList:XMLList;

var urlRequest:URLRequest;

var urlLoader:URLLoader;

var newTrack:Sound;

var newUrlRequest:URLRequest;

var chan:SoundChannel = new SoundChannel();

/* Rewind or FastForward rate */

const SEARCH_RATE:int = 1500;

/* XML file used to load the tracks */

const XML_FILE:String = "tracks.xml";First we create a new Sound object called track and then we initiate some variables that we will require to keep trail of the mp3 file that is being played. Then we define more variables that we will use in our code; these variables include the SoundChannel object.

For our mp3 player, we will be using an XML file to load our tracks. So create a simple xml file named tracks.xml and save it in the same place where your swf and fla files are located. This will be used to store the mp3 information such as track title, track performer, album…etc. mine looks like this. It is ok if yours is different as long as you know how to call the information appropriatley then you are fine, but I recommend you use the same structure to make sure everything works as described:





Performer 1
your_1.mp3



Performer 2
your_2.mp3



Performer 3
your_3.mp3

now we need to be able to access the xml file but first we will load it and then check whether the loading action is complete so type the following after you variables declarations:

// create a new URLRequest object and use to reference the XML file

urlRequest = new URLRequest(XML_FILE);

// create a new URLLoader object to load the XML file

urlLoader = new URLLoader(urlRequest);

urlLoader.addEventListener(Event.COMPLETE, onceLoaded);

urlLoader.load(urlRequest);Don’t test the movie yet if you do you will get an error because we didn’t create onceLoaded function yet, that’s our checking function. The function is added now

function onceLoaded(e:Event):void {

trackXML = new XML(e.target.data);

trackList = trackXML.track;

urlRequest = new URLRequest(trackList[index].path);

track.load(urlRequest);

}This function checks to see if the xml file has completely loaded and then loads the information to our mp3 player.

Adding Functionality to Play Button

Using the instances of buttons created in the previous tutorial we add this to make the buttons respond to our clicking events, the first one is play button:

play_mc.addEventListener(MouseEvent.CLICK, playTrack);Then add the playTrack function that will enable you to play the mp3 when the event of clicking play button as follows:

function playTrack(e:MouseEvent):void {

if (!trackOn) {

newUrlRequest = new URLRequest(trackXML.track[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(trackPos);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

}

}Now you if you test the movie you will be able to hear your first track play when you click the play button. I’m excited already, you?

Adding Functionality to Stop Button

But what if we wanted to the sound to stop? This is where the stop button becomes handy and we do that by adding the following line of code after:

stop_mc.addEventListener(MouseEvent.CLICK, stopTrack);

ffunction stopTrack(e:MouseEvent):void {

if (trackOn) {

chan.stop();

trackPos = 0;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

play_mc.visible = true;

}

}If you test the movie you should be able to play and then stop the sound as you wish. That wasn’t so bad wasn’t it!

Adding Functionality to Next Button

Now we want to enable our mp3 player to jump to another track, because the track we are listening to might be too boring or we are sick of it, after repeatedly listening to it while testing the movie. We do that by adding this code that targets the next button:

next_btn.addEventListener(MouseEvent.CLICK, nextTrack);

function nextTrack(e:MouseEvent):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

}Adding Functionality to Previous Button

Maybe we changed our minds and we want to go back to the same track so what do we do? we add the next lines of code to enable the previous button:

prev_mc.addEventListener(MouseEvent.CLICK, prevTrack);

function prevTrack(e:MouseEvent):void {

if (index > 0) {

index--;

}else{

index = trackList.length() - 1;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

}Adding Functionality to Pause Button

We also want to be able to pause tracks whenever we want. That’s achieved by adding the following code to our action panel;

pause_mc.addEventListener(MouseEvent.CLICK, pauseTrack);

function pauseTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

play_mc.visible = true;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

}

}Adding Functionality to Fast-forward and Rewind Buttons

As it is, your player is already fully functional but we also want to add a fast-forward and rewind functionality to our player. We can add these features by adding the following lines of code in the actionscript panel. First the fast-forward functionality:

ffwrd_mc.addEventListener(MouseEvent.CLICK, ffwrdTrack);

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}and the code for enabling rewind functionality is as follows:

rewind_mc.addEventListener(MouseEvent.CLICK, rwndTrack);

function rwndTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos - SEARCH_RATE);

}

}It is important to add play next function to our fastforward button so that when the track reach the end next track starts, so make changes to ffwrdTrack function as shown by adding chan.addEventListener(Event.SOUND_COMPLETE, playNext); and add the following playNext function as well:

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}

function playNext(e:Event):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(0);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}Displaying Track Information

In order to display track info we need to create some text areas so create two new layers named performer info and title info, respectively and grab the text tool and create two dynamic text areas with Arial type and 11 px. Call the first one performer_txt and second title_txt. This is crucial in order for the code to work properly. Keep each text area in its own layer.

We also need to add some coding to our function in order to display the text when the mp3 player starts playing or next and previous track is selected. Add the following code

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;where necessary in playTrack, nextTrack, prevTrack, and playNext functions. The complete code after re-arranging and adding is shown below:

var track:Sound = new Sound;

var index:Number = 0;

var trackPos:Number = 0;

var trackOn:Boolean = false;

var trackXML:XML;

var trackList:XMLList;

var urlRequest:URLRequest;

var urlLoader:URLLoader;

var newTrack:Sound;

var newUrlRequest:URLRequest;

var chan:SoundChannel = new SoundChannel();

//--- Rewind or FastForward rate ---\\

const SEARCH_RATE:int = 1500;

//--- XML file used to load the tracks ---\\

const XML_FILE:String = "tracks.xml";

urlRequest = new URLRequest(XML_FILE);

urlLoader = new URLLoader(urlRequest);

urlLoader.addEventListener(Event.COMPLETE, onceLoaded);

urlLoader.load(urlRequest);

function onceLoaded(e:Event):void {

trackXML = new XML(e.target.data);

trackList = trackXML.track;

urlRequest = new URLRequest(trackList[index].path);

track.load(urlRequest);

}

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

stop_mc.addEventListener(MouseEvent.CLICK, stopTrack);

next_mc.addEventListener(MouseEvent.CLICK, nextTrack);

prev_mc.addEventListener(MouseEvent.CLICK, prevTrack);

pause_mc.addEventListener(MouseEvent.CLICK, pauseTrack);

ffwrd_mc.addEventListener(MouseEvent.CLICK, ffwrdTrack);

rewind_mc.addEventListener(MouseEvent.CLICK, rwndTrack);

function playTrack(e:MouseEvent):void {

if (!trackOn) {

newUrlRequest = new URLRequest(trackXML.track[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(trackPos);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

}

function stopTrack(e:MouseEvent):void {

if (trackOn) {

chan.stop();

trackPos = 0;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

play_mc.visible = true;

}

}

function nextTrack(e:MouseEvent):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

function prevTrack(e:MouseEvent):void {

if (index > 0) {

index--;

}else{

index = trackList.length() - 1;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play();

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}

function pauseTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

play_mc.visible = true;

play_mc.addEventListener(MouseEvent.CLICK, playTrack);

trackOn = false;

}

}

function ffwrdTrack(e:MouseEvent):void {

if (trackOn){

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos + SEARCH_RATE);

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

}

}

function rwndTrack(e:MouseEvent):void {

if (trackOn) {

trackPos = chan.position;

chan.stop();

chan = track.play(trackPos - SEARCH_RATE);

}

}

function playNext(e:Event):void {

if (index < trackList.length() - 1) {

index++;

}else{

index = 0;

}

chan.stop();

newUrlRequest = new URLRequest(trackList[index].path);

newTrack = new Sound(newUrlRequest);

chan = newTrack.play(0);

play_mc.removeEventListener(MouseEvent.CLICK, playTrack);

trackOn = true;

track = newTrack;

chan.addEventListener(Event.SOUND_COMPLETE, playNext);

title_txt.text = trackList[index].title;

performer_txt.text = trackList[index].performer;

}Adding Spectrum

Our last task is to create a spectrum ……

Create a new layer and call it spectrum then press F8 to create a new empty movie clip call it spectrum. In the editing mode of this newly created movie clip name the first layer rectangle and the second actions. Draw a rectangle 40px wide and 18px high that we’ll use as a guide, so right click the rectangle layer and select Guide. Now add the following code. This is taken from the help file modified a little bit to suite our mp3 player:

addEventListener(Event.ENTER_FRAME, onEnterFrame);

function onEnterFrame(event:Event):void {

var bytes:ByteArray = new ByteArray();

const PLOT_HEIGHT:int = 9;

const CHANNEL_LENGTH:int = 20; //256;

SoundMixer.computeSpectrum(bytes, false, 0);

var g:Graphics = this.graphics;

g.clear();

g.lineStyle(0, 0xFF9933);

g.beginFill(0xFF9933);

g.moveTo(0, PLOT_HEIGHT);

var n:Number = 0;

for (var i:int = 0; i < CHANNEL_LENGTH; i++) {

n = (bytes.readFloat() * PLOT_HEIGHT);

g.lineTo(i * 2, PLOT_HEIGHT - n);

}

g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

g.endFill();

g.lineStyle(0, 0xFF9933);

g.beginFill(0xFF9933, 0.5);

g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

for (i = CHANNEL_LENGTH; i > 0; i--) {

n = (bytes.readFloat() * PLOT_HEIGHT);

g.lineTo(i * 2, PLOT_HEIGHT - n);

}

g.lineTo(0, PLOT_HEIGHT);

g.endFill();

}Back in the main time line just position the empty movie clip where it should and your player should work perfectly. Let me know if you have problems. Later I will upload the files for downloads.

That concludes our tutorial I hope it was clear and helpful to all who want to create fully functional mp3 players. Of course there are more features that can be added to make this player even better, such as track list, elapsed time, mute button, skin color button…etc. but for now this should be sufficient enough. I hope you enjoyed and please leave your comments.

Thank you for reading.



Tags: action script, flash, mp3-player

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
« How to Create an MP3 Player from Design to Finish40 Exceptionally Beautiful Wordpress Themes »Related Posts 26 Responses to “How To Code A Full Functional MP3 Player Using ActionScript 3.0” MAD says:
August 31, 2009 at 8:20 amI should try both tutorials when I am free. But looks great.

Reply j000 says:
August 31, 2009 at 12:55 pmThanks Later I want to experiment with colors and also add more functionality to the mp3 player what do you think?

Reply John says:
August 31, 2009 at 5:43 pmPlease do! Maybe include a settings file to specify colours…

Reply j000 says:
August 31, 2009 at 6:19 pmMaybe in future tutorials this one is a simple mp3 player that is not built using classes.

Reply haungo.net says:
September 1, 2009 at 3:17 amThanks! nice little player there. I’m looking forward to the source.

-B

Reply j000 says:
September 1, 2009 at 8:20 amYeah I will upload it once I figure out how :\ the files are too large maybe without the mp3s!!

Reply j000 says:
September 1, 2009 at 9:03 amSource code and files are available now

Reply 45+ Awesome Links for Web Designers - partytow for all says:
September 2, 2009 at 1:34 am[...] How To Code A Full Functional MP3 Player Using ActionScript 3.0 [...]

Reply Candy says:
September 3, 2009 at 8:36 amHi,
I’ve followed nearly every step of this tutorial, as well as the previous one, and my player looks great, but it doesn’t work.

I created an “actions” layer, and cut and pasted all of your code into this layer. I’m not sure if this is what was intended. Any help would be appreciated!

Reply
j000 says:
September 3, 2009 at 9:13 amActually you right, if you cut and pasted the code into an action layer frame one, then the player should work fine. As long as, you named the instances on the stage with the same names in the actionscript code. Why don’t you download the source files and check if this will help here http://flashjourney.com/wp-content/uploads/2009/08/Creating-Simple-MP3-Player.rar

Let me know if it works and I would love to see how everyone created their mp3 player if a bit different from this.

Reply MP3 Player em Flash com ActionScript 3.0 « Flash Professional says:
September 3, 2009 at 11:58 am[...] Para conhecer o tutorial visite o link: http://flashjourney.com/2009/08/30/how-to-code-a-full-functional-mp3-player-using-actionscript-3-0/ [...]

Reply jufaily says:
September 4, 2009 at 5:20 pmMaybe I will try this with green or blue color for buttons and screen. Cool nonetheless.

Reply Steve says:
September 7, 2009 at 8:58 amHow would you add an autostart feature to this? It’s a great player!

Reply ladas says:
September 9, 2009 at 1:14 amHi! already did the mp3 player it worked fine, but i tried to put it on my web page with everything on it and it doesn’t play.

help please!

Reply MAD says:
September 9, 2009 at 8:06 amHi Ladas, it would help if you can provide more information on your issue. But it might be that the player can not find either the xml file or the mp3 files.

Reply
ladas says:
September 9, 2009 at 3:07 pmthat’s what i thought, because i had uploaded all the files to the same folder. can you tell me why?

Reply
MAD says:
September 11, 2009 at 10:22 amLadas,
you may need to change the following statement to include the full URL where your xml file resides

//— XML file used to load the tracks —\\
const XML_FILE:String = “tracks.xml”;

so instead of only “tracks.xml” you may write “http://yoursite.com/folder/folder/tracks.xml”
You also need to update your XML file to include the full path where the mp3 files are located. This should work, see the demo at the beginning of the article.

Reply Lukaz says:
September 9, 2009 at 10:37 pmHi! I just want to know if it´s possible to start automatically the first mp3 when I execute the swf.
thanks!!

Lukaz

Reply MAD says:
September 11, 2009 at 10:20 amHi Lukaz,
You can update your onceLoaded function as follows; this should do the trick.

function onceLoaded(e:Event):void {
trackXML = new XML(e.target.data);
trackList = trackXML.track;
urlRequest = new URLRequest(trackList[index].path);
track.load(urlRequest);

if (!trackOn) {
newUrlRequest = new URLRequest(trackXML.track[index].path);
newTrack = new Sound(newUrlRequest);
chan = newTrack.play(trackPos);
play_mc.removeEventListener(MouseEvent.CLICK, playTrack);
trackOn = true;
title_txt.text = trackList[index].title;
performer_txt.text = trackList[index].performer;
}
}

Regards,

Reply j000 says:
September 11, 2009 at 7:16 pmNow mp3 demo is active and there are new buttons for downloading and view the demo

Reply MAD says:
September 12, 2009 at 9:39 amA question from Owen Evans:
“Hi there, first just want to say thanks for posting your excellent tutorial on how to create a flash mp3 player. I have one problem thought that I hope you can help me with. After following your tutorial and making a MP3 to my site, I found my site takes longer to load. Is this because it is loading all the mp3 files? Or are they supposed to stream?”

Reply MAD says:
September 12, 2009 at 9:41 amEvans, my guess would be because it is loading all the large mp3 files. You can use The SoundMixer.bufferTime property to stream the file; see an example below:

import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;

var s:Sound = new Sound();
var req:URLRequest = new URLRequest("bigSound.mp3");
var context:SoundLoaderContext = new SoundLoaderContext(8000, true);
s.load
s.true

No comments: