How to build a simple Flash Actionscript 3.0 .mp3 player

Hi there, if you want to build a simple flash mp3 player then this is the right choice to learn. For beginning, this player will have just 3 buttons to manipulate the song (play, pause, stop); will load a single .mp3 file from xml and will have a textfield that will display the song title. In next tutorial we will do this more complex, but for now we will learn just basics.


Preview


Requirements

As usually, you will need: Flash Cs3 (at least), a source code editor ( FlashDevelop) and also you will need Caurina Tweeninig Class for actionscript version 3.0.


Let’s start

Before to start you need to think how this player will be build – the songs will be loaded from outside trough an XML file, the player will have play/stop/pause buttons and will be full OOP actionscript version 3.0, you will be able to stop the song, to pause or play; you will understand all these.

Create a new flash file (index.fla), a new actionscript file (PlayerClass.as) in our class folder (com.fladev.player.PlayerClass.as) and a simple xml file (playlist.xml).


Loading xml

Let’s focus on PlayerClass.as where will load our XML (ex. put a simple trace message and compile index.fla to be sure that everythis is ok).

To do this, we will need to declared in PlayerClass.as some variables, before the constructor:

private var urlLoader:URLLoader;
private const xmlPath:String = "playlist.xml";//xml path
private var xml:XML;

After we declared these variables, we are ready to load the xml content in PlayerClass.as constructor.

public function PlayerClass() {
			urlLoader = new URLLoader();
			urlLoader.load(new URLRequest(xmlPath));
			urlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
		}

		private function xmlLoaded(e:Event):void
		{
			xml = new XML(e.target.data);

			trace(xml);
		}

So we load the path of xml file, we add a listener when is completed and we trace the xml content. Everything is clear so far? If yes, let’s add some songs into playlist.xml file.


Creating XML file

With any editor create a simple xml file (playlist.xml) that will contain a node and a subnode. A subnode will have a song title and a song path:

<song title="Your title" path="Your mp3 path" /><!--this is the data’s subnode-->

That’s it, we finish with xml file. Now we need to add this song into flash.


Loading Songs

In last function “xmlLoaded” from Player.Class.as, after we read the content from xml, we need to add the titles and paths for each song into flash. To do this we store these into 2 arrays and we will manipulate them after. For now declare few new variables:

private var songs:Array;// array for song paths
private var titles:Array;// array for song titles

Initialize these arrays in constructor…

songs = new Array();
titles = new Array();

…and push all song infos into arrays:

private function xmlLoaded(e:Event):void
 {
 xml = new XML(e.target.data);

 for (var i:int = 0; i < xml.song.length(); i++ ) {
 songs.push(xml.song[i].@path);// the "songs" array will contain all paths
 titles.push(xml.song[i].@path);// the "titles" array will contain all titles
 }

 }

After we finish with xml and songs we must create some buttons to control the songs– let’s say play, pause, stop.


Buttons

In index.fla, create a simple movieclip with instance name “bg” – convert this movieclip into another movieclip that will be our button.
Open this movieclip again, locate where bg movieclip is created and create new layer above him – create 3 graphics (one for play, one for pause and one for stop ) and put these graphics on each frame.

So our final button will have one movieclip, that will be the background and above him 3 frames with each graph. Duplicate this button in 3 new ones and give them some instance names (play_btn, pause_btn and stop_btn). Our buttons are almost done but we need to create something more to control them and to respond on any actions (for example rollover or rollout). To do this, we will create a new actionscript file, that wi’ll be our buttons class (Buttons.as). Link all buttons with this new class created, from properties panel in Library and a put a simple trace in this class.

You can customize these buttons as you wish, I will just show you just how to change the background’s color on RollOver or RollOut in Buttons.as. The button’s state release will be in MainClass.as not here.

Add 2 new variables in Buttons.as before constructor:

package com.fladev.player
{
 import flash.display.MovieClip;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import caurina.transitions.Tweener;
 import caurina.transitions.properties.ColorShortcuts;

 public class Buttons extends MovieClip
 {

 private const colorOver:String = "0x2F2F2F"//rollOver color;
 private const colorOut:String = "0x000000"//rollOut color;

 public function Buttons() {
 ColorShortcuts.init();

 Tweener.addTween(bg, { _color:this.colorOut, time:0 } );//fill the background color

 }
 }
}

We need to do few things more: to remove any possible mouse childrens that buttons will contain; to add buttons titles; and finally to create the functions for roll over and roll out. The hole Button.as class will be like this:

package com.fladev.player
{
 import flash.display.MovieClip;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import caurina.transitions.Tweener;
 import caurina.transitions.properties.ColorShortcuts;

 public class Buttons extends MovieClip
 {

 private const colorOver:String = "0x2F2F2F"//rollOver color;
 private const colorOut:String = "0x000000"//rollOut color;

 public function Buttons() {
 ColorShortcuts.init();

 this.mouseChildren = false;
 this.buttonMode = true;

 Tweener.addTween(bg, { _color:this.colorOut, time:0 } );//fill the background color

 this.addEventListener(MouseEvent.ROLL_OVER, over);//add listener on roll over
 this.addEventListener(MouseEvent.ROLL_OUT, out);//add listener on roll out
 }

 private function out(e:MouseEvent):void
 {
 Tweener.addTween(bg, { _color:this.colorOut, time:0.3, transition:"easeOutSine" } );//we change the background color according with colorOver value;
 }

 private function over(e:MouseEvent):void
 {
 Tweener.addTween(bg, { _color:this.colorOver, time:0.3, transition:"easeOutSine" } );//we change the background color according with colorOut value;
 }

 }

}

All right people, our buttons are ready to go. Next and final step is to focus on PlayerClass.as and to turn the music on :)


Play some music…

In PlayerClass.as we have a lot of things to do. We finish with buttons, we change the background color on rollover or rollout, we add a song in XML file and even we push this song into flash, but something is missing. We need to play this song.

To do this, let’s create few more variables for: sound, sound buffer, sound channel, current song, if the song is playing/stopped and also a variable for song position.

private var currentSong:Number  = 0;
private var sound:Sound;
private var context:SoundLoaderContext;
private var channel:SoundChannel;
private var isPlaying:Boolean;
private var isStopped:Boolean;
private var songPosition:int = 0;</pre>
Now let's create the function that load songs.
<pre>private function loadSongs(n:Number) {
			SoundMixer.stopAll();
			sound = new Sound();
			context = new SoundLoaderContext(8000, false);//bufferTime
			sound.load(new URLRequest(xml.song[n].@path), context);//loading the sound path

			channel = sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE, stopSound);

			isPlaying = true;
			isStopped = false;

			title_txt.text = xml.song[n].@title;//song title
		}

If you will compile the index.fla you will hear the song loaded from xml – that’s great so far. But we need to control this song, to stop playing or to pause – and for this we need to create functions for each action. After these function will be done, we will assign them to buttons.

The function that plays a song is:

private function playSound() {//play function
			if(!isPlaying) {
				channel = sound.play(songPosition);//play the song after was paused
				isPlaying = true;
			}

			if (isStopped) {
				loadSongs(currentSong);//if the song is stopped we re-play again
			}
		}

The function that will pause the song is much simple:

private function pauseSound() {//pause function
			if (isPlaying) {
				songPosition = channel.position;
				channel.stop();
				isPlaying = false;
			}
		}

Finnaly, the function that will stop the song to play:

private function stopSound(e:Event=null):void {//stop function
			if (channel != null) {
				channel.stop();
				songPosition = 0;
				isPlaying = false;
			}
		}

The end…

We are very close to finish this tutorial, just some things to check – we create these functions but how we call them? To call these functions from buttons we need to create a single listener in constructur, that will trigger the button’s event:

this.addEventListener(MouseEvent.CLICK, click);

…and the function click for all 3 buttons:

private function click(e:MouseEvent):void {
			switch(e.target.name) {
				case "play_btn":
					playSound();
				break;

				case "pause_btn":
					pauseSound();
				break;

				case "stop_btn":
					stopSound();
				break;
			}
		}

Thank you for your time, hope you enjoy this and learn some basics about creating a flash .mp3 player. Next tutorial I will come with more complex functions then this, but until then, as usually feel free to send me your comments and free sources are bellow. Bye, bye!


Twitter Digg Delicious Stumbleupon Technorati Facebook

20 Responses to “How to build a simple Flash Actionscript 3.0 .mp3 player”

  1. Akwasi Agyemang 14. May, 2010 at 3:47 pm

    need to install trial version of the required software

  2. What can be made using flash mx course?

  3. it is good. i like it.

  4. it is good the like it

  5. Would like to see a volume control as well.

  6. @fred on a next version this will have a volume control too. Until there, stay tuned.

  7. ? Seriously? I was searching Google for how to download songs to a mp3 player and found this… will have to think about it.

  8. GOOD! 支持。 china Malie 好好的分享一下。

  9. The topic How to build a simple Flash Actionscript 3.0 .mp3 player | FlaDev is absolutely new for me, but it´s very interesting. I have to read more about this topic and make me my own opinion. Thanks, Ira Wine

  10. Hi, this is an interesting point, i think there are a lot of things to discuss in the future…

  11. Hello, i´m beginning with rss subscriptions. Now i can stay current with your site and especially the topic How to build a simple Flash Actionscript 3.0 .mp3 player | FlaDev now, really a neat feature. Thanks, Zahnimplantate

  12. Most what i read online is trash and copy paste but i think you offer something different. Keep it like this.

  13. Hi there, please download again the sources. And Merry Christmas

  14. I know it’s verry late, but is it possible to send me your source files?
    I’m a little bit stuck in your code :s

    thnx!

  15. ikeep getting error 1120 Access of undefind property Colorshorts

    Help?

  16. 谢谢,I like it.

  17. Danke!You really do a perfect job!

  18. ColorShortcuts.init()