Flash Action Script 3 MP3 Player Part 1
Here goes Flash Action Script 3 MP3 Player - Part 1. Need Your comments and support on the articles.
I am writing this first version of Flash Action Script 3 MP3 for beginners so that they can have an idea of Flash Action Script 3 Sound Classes. Also this code uses memory optimization techniques to reduce memory leaks.
To Learn More About Memory Optimization read my previous post
http://actionscript-blog.imaginationdev.com/Memory-Optimization-Flash-Action-Script-3
Flash Action Script 3 MP3 Player can be developed in 2 ways. 1- Songs are played once they are completely downloaded on the local machine, Part 1 of my Flash Action Script 3 MP3 Player uses this techniques. this approach is suitable when developing a desktop application. 2- Songs are buffered and streamed from the server and played simultaneously. This type of approach is common for Online Flash Action Script 3 MP3 Player. Part 2 of this article series will cover the 2nd methodology.
Building a Flash Action Script 3 MP3 Player is really easy using Flash Action Script 3 classes. Once you have the concepts of Sound class, SoundChannel class and Timer class in Flash Action Script 3 you are ready to develop a Media Player in Flash Action Script 3. In case you need guidance and help in the above mentioned classes you are welcome to leave comments and i will respond as soon as possible.
This might not be the best Flash Action Script 3 MP3 Player. This sure will guide you how to develop a Flash Action Script 3 MP3 Player using flash action script. There are number of flash media players available on the internet but very few i saw focussed on the fact that action script sound class has some problems when optimizing memory space. So i thought to write one sample of my own.
This flash MP3 player is easily customizable and reusable. In coming future i plan to write a Flash MP3 Player Component using Action Script3. Hopefully that article will also cover the basis of creating a flash component.
You can use the flash action script 3 Mp3 player code to build your own customized Flash Action Script 3 MP3 Players. Basic idea will always remain the same.
Flash Action Script 3 MP3 Player development starts with the code for loading XML and inserting data in the play list.
/////////////////////////////////////////////////////////////////
//Loading XML
/////////////////////////////////////////////////////////////////
var xmlData:XML; var xmlLoader:URLLoader = new URLLoader();xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("playlist.xml"));
function LoadXML(e:Event):void {
trace(LoadXML); xmlData = new XML(e.target.data);
function getValues(input:XML) {
var xmlCategoryList:XMLList = input.children(); var item:XML;var intCount:int = 0;
for each (item in xmlCategoryList) {
playList.addItem({label:item.title, data:item.url}); intCount = intCount + 1;
}
}//end of get Values Function
getValues(xmlData);
}// end of Load XML
After that we will wait until user clicks on any song in play list. For handling play list event we will write the following code.
playList.addEventListener(Event.CHANGE, playListChangeHandler);
function playListChangeHandler(event:Event) {
if (flagSoundChannel==1) {
soundChannel.stop();
} else if (flagSoundChannel==0) {
flagSoundChannel=1;
}
playSound(event.target.selectedItem.data);timeSlider.value=0;
}// end of change Handler
Above code calls another important function playSound. This method loads the new sound in the sound Object.
function playSound(path) {
songPath.url = path;
if(playerObject.sound!=null)
delete playerObject.sound;
playerObject.sound = new Sound();
addSoundEvents();
playerObject.sound.load(songPath);
}
Above code requires sound events to be handled before a new sound object is created. If you focus on the delete playerObject.sound; statement, this deletes the previous allocation of memory for the sound object. If we don’t do this a lot of memory will leak and eventually application will crash.
/////////////////////////////////////////////////////////////////
//Sound Loading Event Handler Function
/////////////////////////////////////////////////////////////////
function addSoundEvents():void
{
playerObject.sound.addEventListener(Event.COMPLETE, funcSoundLoaded);
playerObject.sound.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
playerObject.sound.addEventListener(ProgressEvent.PROGRESS,funcOnLoadProgress);
}
function funcSoundLoaded(event:Event) {
var soundObject:Sound = event.target as Sound;
var totalSoundDuration:Number;
soundChannel=soundObject.play();
totalSoundDuration=(soundObject.length/1000)/(60);
totalSoundDuration=Math.floor((totalSoundDuration*100));
totalSoundDuration=totalSoundDuration/100;
timeSlider.maximum=(soundObject.length/1000);
sliderDivisionValue=totalSoundDuration;
fileTimeInSec = Math.floor(playerObject.sound.length/1000);
secTimer.start();
}//end of Function Loaded
function funcOnLoadProgress(event:ProgressEvent):void {
var loadedPct:uint =Math.round(100 * (event.bytesLoaded / event.bytesTotal));
trace("The playerObject.sound is " + loadedPct + "% loaded.");
}
function onIOError(e:IOErrorEvent) {
trace("The playerObject.sound can not be Loaded"+ e.text);
}
Above is code implementation of sound event handlers. Lastly we will add Timers and GUI element event handlers.
/////////////////////////////////////////////////////////////////
//Control Handlers UIDesign
/////////////////////////////////////////////////////////////////
btnStop.addEventListener(MouseEvent.CLICK,funcStop);
btnPause.addEventListener(MouseEvent.CLICK,funcPause);
btnPlay.addEventListener(MouseEvent.CLICK,funcPlay);
btnForward.addEventListener(MouseEvent.CLICK,funcForward);
btnBack.addEventListener(MouseEvent.CLICK,funcReverse);
soundChannel.addEventListener(Event.SOUND_COMPLETE, funcComplete);
function funcComplete(event:Event) {
soundChannel.stop();
timeSlider.value=0;
currPosition=0;
}
function funcStop(event:Event) {
secTimer.reset();
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
function funcPause(event:Event) {
secTimer.stop();
currPosition= soundChannel.position;
soundChannel.stop();
btnPlay.visible=true;
btnPause.visible=false;
}
function funcPlay(event:Event) {
soundChannel.stop();
soundChannel=playerObject.sound.play(currPosition);
btnPlay.visible=false;
btnPause.visible=true;
secTimer.start();
}
function funcForward(event:Event) {
if (soundChannel.position+forwardDuration<=playerObject.sound.bytesTotal) {
timeSlider.value+=forwardDuration/1000;
soundChannel.stop();
soundChannel=playerObject.sound.play(soundChannel.position+forwardDuration);
}
else
{
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
}
function funcReverse(event:Event) {
if (soundChannel.position-forwardDuration>0) {
timeSlider.value-=forwardDuration/1000;
soundChannel.stop();
soundChannel=playerObject.sound.play(soundChannel.position-forwardDuration);
}
else
{
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
}
/////////////////////////////////////////////////////////////////
//Control Handlers Sliders
/////////////////////////////////////////////////////////////////
timeSlider.addEventListener(SliderEvent.THUMB_PRESS,sliderPressed);
timeSlider.addEventListener(SliderEvent.THUMB_RELEASE,sliderReleased);
timeSlider.addEventListener(SliderEvent.CHANGE,sliderChangeHandler);
timeSlider.liveDragging =true;
function sliderChangeHandler(event:SliderEvent) {
secTimer.stop();
soundChannel.stop();
soundChannel=playerObject.sound.play(event.target.value*1000);
secTimer.start();
}
function sliderPressed(event:SliderEvent) {
}
function sliderReleased(event:SliderEvent) {
secTimer.stop();
soundChannel.stop();
soundChannel=playerObject.sound.play(event.target.value*1000);
secTimer.start();
}
/////////////////////////////////////////////////////////////////
//Control Handlers Timers
/////////////////////////////////////////////////////////////////
secTimer.addEventListener(TimerEvent.TIMER, onTick);
secTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
function onTick(event:TimerEvent):void {
trace("Timer is running");
timeSlider.value+=1;
}
function onTimerComplete(event:TimerEvent):void {
trace("Time's Up!");
}
For Further details on voice control and sound buffering you may contact me. I will soon be writing part 2 of the flash MP3 Player series with voice control and Sound Buffering.
Kindly Let me know about your remarks if this article is being helpful in solving your problem.
Download Sample Project : Flash MP3 Player Using Action Script 3
A running sample can be viewed at the following link
www.imaginationdev.com/actionscript-blog/samples/mp3-player/play.html
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.
Comments
I have tried modify your script in an effort to add a spectrum analyser effect, but so far failed, not that I won’t keep trying, it is to my mind the best starting point I have found.
I do have a wish list of things I would like to see on this mp3 player and maybe if I list them you could explain how it could be done.
Adding a text field such as CDATA information such as lyrics and artwork?
How do you add a spectum analyser to your code?
I look forward to your next article.
John
[Reply]
Next article i will soon add up . I will add up sepctrum on the MP3 as well . Hope fully this week end i will find enough time to do that. I have the files but did not got time to upload it yet .. Also I would Appreciate if you would add my blog on your site. Cause Support from your guys will encourage me to put more and more articles to help action script Community
Thank you
[Reply]
Yeah that sounds a good idea, once my new revamped site is up and running. I have struggled over the past week to figure out where in your code to add my dynamic text fields.
title_txt = ?.title;
All I do is cause it to error.
[Reply]
hi, where are you trying to add the dynamic field and for what use ? i didnot understand the problem clearly ?
can you explain a bit more.
Have a nice day
[Reply]
The dynamic fields that I would like to add would bring up things like the title of the song, lyrics, infomation about the song. That sort of thing.
Cheers
John
[Reply]
My idea is that when someone selects a song they want to hear, the player shows in a dynamic text field which song is currently playing, maybe with it scrolling length of the song, artist?
But when a song is selecte it also can bring up what is the xml data, such as a fields that listed such as below ..
title of song
link to where you can download the song
etc..
I am not sure whether the CDATA info should come from a mysql database what do you think?
I love flash and mysql/php and have taught myself quite a bit, but to develop in AS3 seems a minefield. You see many examples of MP3 players some of them that do some cool spectrum analysers, but none of them as well written as your own. Looking at the work others have achieved shows what could be done, that is if you are as up on AS3 as yourself. I am eager to learn AS3 although this seams to be the undiscovered country, especially when you combine creating an mp3 player that can do the above and combine a menu system built using papervision technology which also uses AS3. This stuff is at the cutting edge.
Thanks again
John
[Reply]
you can add that information in the xml file and can display it on any dynamic feild i guess that should not be a problem . Are you using flash cs3 ?
[Reply]
Just curious where you’re at with part 2, for pseudo streaming. This one seems to work great other than delay with initial downloading before playing. Thanks for post. It’s one of better ones on MP3 player.
[Reply]
great article! just what i was looking for. haven’t used flash since actionscript 1 and it’s changed a whole lot.
saw one small bug in the example - if you stop a playing track, then the play/pause button stays on pause instead of resetting to play.
[Reply]
Hey man, sweet tutorial.
You had mentioned contacting you for voice control which I would like to implement in a platformer for school.
Any help would be greatly appreciated.
[Reply]
Hi , what kind of help you are looking for my friend . You can email me at mbilal@imaginationdev.com
[Reply]
hey…thanx I m new to this field and your codes are helping me lot.
nways please can u put some more comments for better understanding of freshers like me..
thanx once again.
[Reply]
FYI: Looks like Adobe can’t handle two and more instances on Flash plugin in the same browser and handle SoundChannel.stop/Sound.play correctly. I have the similar application and it crashes IE, same way crashes yours:
- load player in one tab (IE7, Windows XP or Vista)
- open second tab, load your player and play anything
- move audio position knob back and forth few times
- eventually you’ll get it, IE crashes.
[Reply]
How do you change the list color of the items in playList?
[Reply]
Hi Roshan , next time i will put up more comments on .. Thanks for your suggestions
[Reply]
First let me say thanks for posting this tutorial.
I have modified the player a bit and was able to display elapsed time and total time but cannot get the track name to display.
Also, I was wondering how to get the first song to play as soon as the xml is loaded (instead of waiting for the user to choose).
If anyone has any idea how to get this done please let the rest of us know.
Oh, for those of you wondering how to display the time, do the following:
For total time create a dynamic text box, give it an instance of displayFullTime, and paste this at the end of the function funcSoundLoaded.
displayFullTime.text = ( ” ” + totalmins+ “:” + totalsecs);
For time elapsed create a dynamic text box, give it an instance of displayTime, and paste this at the end of the functions sliderChangeHandler and onTick.
displayTime.text = ( ” ” + totalmins+ “:” + totalsecs);
[Reply]
A quick correction to my previous post.
For total time:
var tallytime = (soundObject.length/1000);
var totalmins:Number = Math.floor(tallytime /60);
var totalsecs = Math.floor (tallytime) % 60;
if (totalsecs < 10){
totalsecs = “0″ + totalsecs;
}
displayFullTime.text = ( ” ” + totalmins+ “:” + totalsecs);
For time elapsed:
var totalSeconds:Number = soundChannel.position/1000;
var minutes:Number = Math.floor(totalSeconds /60);
var seconds = Math.floor (totalSeconds) % 60;
if (seconds < 10){
seconds = “0″ + seconds;
}
displayTime.text = ( ” ” + minutes+ “:” + seconds);
[Reply]
Hello,
I was looking through your coding for the mps player in AS3.0 and I was wondering what coding do I put in an external XML file and where in the coding do i put my songs? I’m really new to AS3.0 and for my mp3 player I just have the buttons (previous, pause, play, next). I don’t need the display name or any of the other stuff.
Please advise?
[Reply]
[...] know how to code it or anything but if you need anything i can give it to you. tutorial i used Flash Action Script 3 MP3 Player Part 1 now i just need a volume leveler and mute/unmute button so anyone who can help it’d be [...]
Hi,
I have been creating an mp3player as well, where i put the focus on memory management. I came quite far but still there is a little amount of memory leaking. So I came across your MP3player script.
Unfortunately, from the url to the working example on here, I manage to get the memory of FF3 from 70MB to 150MB, and it was still going on with leaking memory.
It seems that the sound object in your script also accepts multiple mp3 files being played over the same channel.
The problem that I am facing, is that the memory leak is most when switching a playlist (this is done with a combobox, that contains multiple playlists, which are being loaded into a List control).
The problem is that Flash does not garbage collect anything that has a reference. Therefore I had the following solution.
I create an instance of a MP3Player class, which does all the loading, computespectrum, soundlevels, progress etc.
On each song that is selected, all listeners to this instance are being removed and the instance itself is set to null in the Main document class.
After its being set to null, I force Flash Player manually to garbage collect by using System.gc(). If I monitor the memory, It seems I need to call the System.gc() multiple times (I did it with a Timer) before it frees memory.
A great way to see if an object instance is really being removed and only exist once in your application and how much memory it uses, is to use the Flex debugger. I use Flex in Eclipse, only for the debugger, but it gives the possibility to profile your Flash app from out your Flash IDE.
However the problem is, that Flash player puts the mp3 file in it’s cache, causing the memory slowly to grow.
[Reply]
btw, Eventhough I am still tweaking and making the code more generic, If anybody is interested in my source code, just let me know.
[Reply]

Great article, I especially like the format you use of xml, which should allow me to include lyrics and images.
I look forward to reading part two.
[Reply]