Flash Essential

MP3 Player In AS3

Jun 4th 2008
53 Comments
respond
trackback

In this tutorial you'll learn how to create your very own Ipod player using actionscript 3. We'll load in our music files from an XML file, take all the artist song and album data from that file and load it into our fla file. We wont be looking into the XML file in great detail in this tutorial but I hope to cover that in future tutorials.

Download

Starter and Finished Files

Take a Look

View The Finished File

I recommend you look at the Finished File as I've given a more in depth code explanation inside the actions panel.

note; I haven't added any songs in the songs folder so you'll have to add your own for it to work!

First lets look at what we have in our starter file. On the stage we have an Ipod with play, pause, back and forward buttons all with the instance names pause_btn, play_btn, prev_btn and next_btn respectively. The first thing we'll do is create some dynamic text boxes to load our song text into, so lets get to it.

Step 1 - Dynamic Text

Select the Text Tool and makes sure Dynamic Text is selected in the Properties Panel at the bottom. Draw out a text box on the Ipod screen and give it the instance name artistTXT. Do that twice below the the first text box and give them the instance names albumTXT and songTXT.

Mp3 Player Step 1

Step 2 - Add Our Actionscript

Go to the actions layer and open up the actions panel, The first thing we are going to do is add our variables. So go ahead and copy and paste the code below.

var getMusic:URLRequest;
var music:Sound = new Sound();
var soundChannel:SoundChannel;
var currentSound:Sound = music;
var pos:Number;
var currentIndex:Number = 0;
var songPlaying:Boolean = false;
var xml:XML;
var songlist:XMLList;

Step 3 - Preloader

We'll create a simple preloader to load our content in.

function loadProgress(event:ProgressEvent):void {
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
if(percentLoaded > 20){
trace("loading");
} else{
}
}
function completeHandler(event):void {
trace("DONE");
}

Step 4 - Load In The XML

Here we load in our XML and create a function that will run when our loader has completed loading.

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, whenLoaded);
loader.load(new URLRequest("songs.xml"));

function whenLoaded(e:Event):void
{
xml = new XML(e.target.data);
songlist = xml.song;
getMusic = new URLRequest(songlist[0].url);
music.load(getMusic);//load music
soundChannel = music.play();
songTXT.text = songlist[0].title;
artistTXT.text = songlist[0].artist;
albumTXT.text = songlist[0].album;

soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

Step 5 - Add Event Listeners For Buttons

Now we'll add some Mouse Events for our buttons on the ipod and give them some functions.

next_btn.addEventListener(MouseEvent.CLICK, nextSong);
prev_btn.addEventListener(MouseEvent.CLICK, prevSong);
pause_btn.addEventListener(MouseEvent.CLICK,pauseSong);

function nextSong(e:Event):void
{
if (currentIndex < (songlist.length() - 1))
{
currentIndex++;
}
else
{
currentIndex = 0;
}

var nextReq:URLRequest = new URLRequest(songlist[currentIndex].url);
var nextTitle:Sound = new Sound(nextReq);
soundChannel.stop();
songTXT.text = songlist[currentIndex].title;
artistTXT.text = songlist[currentIndex].artist;
albumTXT.text = songlist[currentIndex].album;
soundChannel = nextTitle.play();
songPlaying = true;
currentSound = nextTitle;
soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

function prevSong(e:Event):void
{
if (currentIndex > 0)
{
currentIndex–;
}
else
{
currentIndex = songlist.length() - 1;
}

var nextReq:URLRequest = new URLRequest(songlist[currentIndex].url);
var prevTitle:Sound = new Sound(nextReq);
soundChannel.stop();
songTXT.text = songlist[currentIndex].title;
artistTXT.text = songlist[currentIndex].artist;
albumTXT.text = songlist[currentIndex].album;
soundChannel = prevTitle.play();
songPlaying = true;
currentSound = prevTitle;
soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

function pauseSong(e:Event):void
{
pos = soundChannel.position;
soundChannel.stop();
songPlaying = false;
play_btn.addEventListener(MouseEvent.CLICK,playSong);
}

Conclusion

This a pretty basic Mp3 player, I hope it's given you an idea how to work with sound in Actionscript 3. Make sure you look at the Finished File for a more in depth explanation of the code.


This post is tagged , , , ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



53 Comments

  1. I put my own MP3 in the songs folder and changed the XML document correctly but when I test the finished .swf file I get no song….

  2. admin

    Hi Austin,

    I double checked the download file and everything is fine. What error are you getting in the output window? I suspect there is a problem with your xml file, so I suggest you double check it. Feel free to send me through the files at Matt@FlashEssential.com so I can take a closer look at the problem.

    cheers.

  3. Clinton

    I really like the player you've created. I'm trying to stop the music from playing once the page is loaded…I would like for the music to start once the viewer has pressed play rather than it starting automatically.

    Do you have any recommendations?

  4. admin

    Hi Clinton

    inside the whenLoaded function add these lines of code;

    soundChannel.stop();
    play_btn.addEventListener(MouseEvent.CLICK,playSong);

    that should work I think.

    Thanks

  5. wow looking cool!!!tnx for this one:)keep up a good work

    NaldzGraphicss last blog post..300+ Best of the Best High Quality Abstract Brushes in Photoshop

  6. Yes very cool. Thanks

  7. I inserted player to my site using this code:

    In firefox, everything works fine, but in IE it doesn't. How could I solve this problem?

  8. Somehow script wasn't showed in previous post…
    object class="player" type="application/x-shockwave-flash" data="flash/ipod.swf"
    param name="wmode" value="transparent" /
    /object

  9. admin

    Martin,

    I recommend downloading http://code.google.com/p/swfobject/ for embedding flash content.

    I'll be posting a tutorial on how to use swfobject next week so look out for that.

  10. Look at this site (www.rockamhoerstein.at) it won't work. Action Script is the same as the sample file - help!

  11. admin

    Hi Steve,

    What errors is it giving you?

  12. OsvaldQ

    I tried including the code to make the player stop playing when loaded:

    Hi Clinton

    inside the whenLoaded function add these lines of code;

    soundChannel.stop();
    play_btn.addEventListener(MouseEvent.CLICK,playSong);

    but it didn't work. Anything I have missed?

    thanks
    Oz

  13. fkid

    i appreciate your script, i like it for being so basic.

    one problem: i dont get the player to stop when loaded either.

    thanks for your help,
    fkid

  14. Roger

    Try deleting the line

    soundChannel = music.play();

    and the line

    soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);

    and insert the following line:

    play_btn.addEventListener(MouseEvent.CLICK,playSong);

  15. Thanks for the tutorial, it's really clear and easy to understand.

    I'm new to AS and taking a AS3 class and finding it very difficult. Anyway, I'd like to incorporate this code into a small player on the flash site that I am using. I already have my own buttons created as movieclips, and replaced the names of your buttons with my own. However, when I compile I receive many errors, first being "Access of unidentified property, loader"

    Again, all I have done so far is enter your code into my actionscript file for my site.

    Any help is appreciated.

    Thanks!

    Chris

    Chriss last blog post..Defoe and Associates Logo Design Concept

  16. Great player but I have one question…

    I also have buttons pertaining to each individual song. How would I get those buttons to play their assigned song when pressed?

  17. admin

    Chris, could you email me the files your having problems with so I can take a closer look?

    Matt@FlashEssential.com

    Myke, I'll look into that.

  18. mg

    Hi , thanks I'm having fun to understand that ! I'm trying to upgrade it with a selectable list … is it a good idea to try with the list component? i succsed to display the list but I try to change the song when i select one , but i'm lost there… do you have some clue ?
    Thanks

  19. mg

    ok i found it : its selectedIndex :)

  20. admin

    Glad you got it sorted MG.

    Just to give you the heads up folks

    Im creating a new player that'll be launched next week…

    hopefully..

  21. Budz

    in addition to this player.
    I notice that, there is no stop button
    so I created stop button

    hopefully this little code that i was created can help you.

    CODE:

    stop_btn.addEventListener(MouseEvent.CLICK, stopSong);

    function stopSong(event:Event):void
    {
    soundChannel.stop();
    pos = soundChannel.position;
    songPlaying = false;
    play_btn.addEventListener(MouseEvent.CLICK,playSong);
    }

    Thanks to the admin….

  22. Budz

    next time i will post a code for the volume control.

  23. Linxx

    Hi, I am new to flash so this may sound like a real dumb question so bare with me, but anyway how do I manage to load my xml file into flash?

  24. annaroy

    how do i create a javascript add playlist with this script

  25. annaroy

    like javascript:function(path)

  26. Brilliant! I liked the u explained code in this tut.

  27. AGuy

    I noticed there is no playSong method. What is being call from the flay button event listener?

  28. As I promised
    Here is the code for Volume Control.

    NOTE:
    re-skin the player first.

    Create a rectangle W= 100 H= 10 convert it to movie clip and give an instance name volume_mc registration center in the left .
    Double click the volume_mc and create a new layer then also create a square or circle W=15 H=15 and convert it to movie clip, regitration center give an instance name mySlider_mc lastly create a dynamic text give an intance name volPercent

    CODE:

    var rectangle:Rectangle = new Rectangle(0,0,100,0);
    var dragging:Boolean = false;
    var bounds:Object = {left:0, right:100};

    volume_mc.buttonMode=true;
    volPercent.selectable = false;
    volPercent.autoSize = "center";

    volume_mc.mySlider_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);

    function startDragging(event:Event):void {
    volume_mc.mySlider_mc.startDrag(false,rectangle);
    dragging = true;
    volume_mc.mySlider_mc.addEventListener(Event.ENTER_FRAME, adjustVolume);
    }

    function adjustVolume(event:Event):void {
    var Vol:Number = volume_mc.mySlider_mc.x / 100;
    var soundTransform:SoundTransform = new SoundTransform(Vol);
    if (soundChannel != null);
    {
    if(dragging = true)
    soundChannel.soundTransform = soundTransform;
    }

    stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

    function stopDragging(event:Event):void {
    if (dragging) {
    dragging = false;
    volume_mc.mySlider_mc.stopDrag();
    }
    volPercent.text = Math.round((volume_mc.mySlider_mc.x-bounds.left)/(bounds.right-bounds.left)*100) + "%";

    }
    }

  29. hi AGuy,

    here is the code for you.

    CODE:

    play_btn.addEventListener(MouseEvent.CLICK,playSong);

    function playSong(e:Event):void
    {
    soundChannel = currentSound.play(pos);
    soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
    songPlaying = true;
    play_btn.removeEventListener(MouseEvent.CLICK,playSong);
    }

  30. jaxz

    Hi, i'm learning AS 3 using CS4.

    When I try step 5 to add the event listeners, I get an error saying:
    " The actions on the clipboard contain errors. Actions with errors cannot be pasted in script assist mode "

    Please advice!!

    Cheers,
    Jaxz

  31. jaxz

    also, when I turn off the script assist mode and just paste the event listener code in below the code given in steps 2-4, I get the following compilation error:

    Location:
    scene 1, Layer "actions", Frame 1, line 32

    Description:
    1093: Syntax error.
    Source:
    currentIndex-;

    on line 32 the script reads:

    soundChannel = music.play();

    ?
    Please advice!

    Jaxz

  32. jaxz

    Silly me, trying the final version shows that the code is correct. Must be some glitch in my pasting ability…

    Thanx admin and thanx Budz for completing extra features!

    Cheers,
    jaxz

  33. jaxz

    Budz!
    I got your stop_btn to work - thanx!

    Still, the volume control part gives me an error:

    TypeError: Error #1010: A term is undefined and has no properties.

    I have created a 100*10 rectangle, made it a movieclip given instance as you say, and created a 15*15 rectanglge also into movieclip and instancecname. I also created a dynamic textbox. then I pasted the code at the end of the working actions script.

    I don't understand what you mean by "registration center in the left " - I just positioned the rectangles and text box by putting numbers into the position/size under properties.

    Perhaps this issue is what causes the problem. My new rectangles and text box just sit there on the Ipod like graphics.

    Can you please advice me - I can send you my file if you can look at it?

    regards,
    jaxz

  34. budz

    jaxz download this sample file.

    note:
    put them together to download and put it in you address box & hit enter.

    http : // rapid share. com / files / 197015494 / Sample. rar. html

  35. budz

    hope it will help.

  36. jaxz

    THanx bunches Budz - I get your file to run nicely!
    I'll see how I can learn more from your example!

    Cheers,
    jaxz

  37. thanks very much for this tutorial.
    as a novice, it explains a lot.

    so i built the code as you said, loaded great!
    now, I have a question:

    how do i add an image_mc function:
    the script assist says it does not support loading the .MovieClip

    songTXT.text = songlist[0].title;
    artistTXT.text = songlist[0].artist;
    albumTXT.text = songlist[0].album;
    *** image_mc.MovieClip = songlist[0].MovieClip; ***
    Do I need to add a new var loader and an event listener

    any help is much 'preciated.

  38. I'm trying to the the code to work that makes the file stop playing when it loads. I've tried all of the suggestions here and I always end up with a file that will only start playing if you skip to the next song. I need help!

    Jareds last blog post..Official Notice

  39. budz

    hi jared,

    try this one code:

    Step 2 - Add Our Actionscript

    find this code; var pos:Number;
    and replace to this code
    var pos:Number=0;

    just let me know if it is work.

  40. Voxunum

    Is there any way that I can embed this player in a Action Script 2.0 site or any modifications that can be done to either file to make this Action Script 3.0 to work with Action Script 2.0? Thanks for the help

  41. yes, i love this tut.
    I will try this and hope to have an unique player in my blog.

  42. flash

    Hey it's a great tutorial but i have a question

    i have 4 song in one album but i want to add another album which has another 3 songs. But i don't want the next album's songs to start playing until the user clicks on it. when the album ends i just want it to stop

    have any idea how to do that

    help appreciated

  43. flash

    And also i was trying the code for the volume control it gives me this error

    TypeError: Error #1010: A term is undefined and has no properties.
    at ipod_fla::MainTimeline/frame1()

    does anyone know the solution

  44. Bigguy

    hey budz could you please upload the sample file up because when i try and download it says the file no found

    thanx bro

  45. Budz

    hi Bigguy,

    download this file

    _http://_rapidshare.com/_files/230885129/sample._rar.html

    just remove _

    in addition to this player I created an extra features
    like stop button, mute button and volume control.

    just let me know Bigguy if it it's work for you
    I tested it and works 100%

  46. DTB

    Hi,

    Really great tutorial, respect for the author! But, I missing the "seeker" from the player, and I can't do that! :(

    Have any idea how to do that?

    Thanks

  47. Bigguy

    Hey Budz that is sweet
    but you reckon you know the code for how to make the seeking bar
    if you do or know any website that has it, it would be great

    thanks for the file
    really appreciated

  48. Budz

    try this bigguy

    __http://www.tutorialized.com/view/tutorial/-AS-3.0-XML-MP3-Player/42092

  49. Budz

    next time I post a complete update of this player with seek bar and the time duration also a compute spectrum but for now i don't have time to upload the sample.

  50. Budz

    a simple thank you in exchange to this download link….

    _http://rapidshare.com_/files/247268799/_mp3PlayerCS4.rar.html

    NOTE: remove the _

  51. veeru

    juust i was trying to create a Slider When A song is playing that slider will go to some x- position

    plz give me feedback……..

Leave a Reply