Bees Are Social By Nature

Transcribed thoughts and experiences about computer programming.

Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2

After creating a Simple FLV Player using ActionScript 3.0, I decided to extend my learning by going through the process of creating a simple MP3 player using ActionScript 3.0 and Flex 2. For requirements, all I wanted my MP3 player to do was play from a static list of MP3 files and have controls allowing me to play, pause, stop, go to the next song in playlist, and go to a previous song in the playlist. I have seen quite a few of these floating around the internet, so I figured it should be pretty easy and, as expected, it was.

Prerequisites:

Flex 2 SDK: http://www.adobe.com/products/flex/sdk/
Public Domain MP3 Files: http://www.publicdomain4u.com/

1) Install Flex 2 SDK

After downloading the flex_sdk_2.zip, I just unzipped the contents in to a work folder, c:\flex_sdk_2. The key resources I used from this package with were the compiler, bin\mxmlc.exe, and the debug Flash player (player\debug\SAFlashPlayer.exe).

2) I generated the following source in my favorite text editor, please note that I decided to go with the “source is the documentation” style of documentation for what and why I did:

The ActionScript source for the mp3 player class, SimpleSimpleMP3Player.as:

package { 
    import mx.containers.Panel; 
    import mx.controls.Button; 
    import flash.events.*; 
    import flash.media.Sound; 
    import flash.media.SoundChannel; 
    import flash.net.URLRequest; 
    import flash.utils.Timer;     

    public class SuperSimpleMP3Player extends Panel { 
    	// Song List 
    	private var songURLs:Array = 
    	    ["SongFromCottonField.MP3", 
	     "Bill_Cox--My_Rough_and_Rowdy_Ways.mp3", 
	     "Robert_Johnson-Love_In_Vain.mp3", 
	     "Andy_Iona-Naughty_Hula_Eyes.mp3", 
	     "AtlantaBound.MP3", 
	     "MamieSmithHerJazzHounds-CrazyBlues.mp3"];     

        // Current Song to Play 
        private var currentIndex:Number = 0;     

        // Sound Channel to monitor 
        private var song:SoundChannel;     

        // Request object for obtaining mp3 
        private var request:URLRequest     

        // Pause state management 
	private var paused:Boolean = true;     

	// Stopped state management 
	private var stopped:Boolean = false;     

	// Retains what position the song was in 
	// when it was paused, so we can go back to 
	// the same position when we hit play again. 
	private var position:Number;     

	// Sound... Factory for initializing our song. 
        private var soundFactory:Sound;     

	// The magic var that allows us to set the actual 
	// implementation of the play button from the Flex 
	// MXML.  This allows a custom component, see 
	// SimpleMP3.mxml, to set the actual button that 
	// playButton referres to, letting us change the 
	// label, or any other property of the button in 
	// our ActionScript. 
	public var playButton:Button;     

        public function SuperSimpleMP3Player() { 
            super(); 
	    playMP3(currentIndex);     

        }     

	// Play MP3 at specified index in songURLs array. 
	public function playMP3(mp3Index:Number):void { 
	    stopped = false; 
	    paused = false; 
	    position = 0; 
	    var request:URLRequest = 
	        new URLRequest(songURLs[mp3Index]); 
	    soundFactory = new Sound(); 
	    soundFactory.addEventListener(Event.ID3, id3Handler); 
	    soundFactory.load(request); 
	    song = soundFactory.play(); 
            song.addEventListener(Event.SOUND_COMPLETE, 
                soundCompleteHandler); 
	}     

        // Since the id3 information is not available until it 
        // is read off the string we need to make sure we have 
        // a way of updating the UI once it has been loaded. 
        // Having songName as a bindable allows us to do that, 
        // and the id3Handler will notify us when the information 
        // is ready to be displayed. 
        [Bindable("songNameChanged")] 
	public function get songName():String { 
		return soundFactory.id3.artist + 
			" - " + soundFactory.id3.songName; 
        }     

	// Alert songNameChanged bind when id3 information 
	// has been loaded. 
        private function id3Handler(event:Event):void { 
            dispatchEvent(new Event("songNameChanged")); 
        }     

	// Start the next song, once the current one has 
	// finished playing. 
	private function soundCompleteHandler(event:Event):void { 
	    position = 0; 
	    currentIndex++; 
	    if (currentIndex >= songURLs.length) { 
	        currentIndex = 0; 
	    } 
	    playMP3(currentIndex); 
        }     

	// Pause current song, or play song if already paused. 
	// Setting playButton label such that any GUI button 
	// that is attached will change with play or pause. 
	public function pause():void { 
	    if (!stopped) { 
	        if (!paused) { 
	    	    paused = true; 
		    position = song.position; 
		    song.stop(); 
		    playButton.label = ">"; 
	        } else { 
		    paused = false; 
		    song = soundFactory.play(position); 
		    song.addEventListener(Event.SOUND_COMPLETE, 
		    	soundCompleteHandler); 
		    playButton.label = "||"; 
	        } 
	    } else { 
	        playMP3(currentIndex); 
	        playButton.label = "||"; 
	    } 
        }     

	// Stop current song 
	public function stop():void { 
		stopped = true; 
		song.stop(); 
		position = 0; 
		playButton.label = ">"; 
	}     

	// Switch to Next Song 
	public function next():void { 
	    currentIndex++; 
	    if (currentIndex >= songURLs.length) { 
	        currentIndex = 0; 
	    }     

	    song.stop(); 
	    position = 0;     

	    // Track if player was already playing, 
	    // paused, or stopped. If stopped or 
	    // paused, still "play" so we can start 
	    // streaming and obtain the id3 info.     

	    var wasStopped:Boolean = stopped; 
	    var wasPaused:Boolean = paused;     

	    playMP3(currentIndex);     

	    if (wasStopped) { 
	        stop(); 
	        return; 
	    }     

	    if (wasPaused) 
            { 
		paused = true; 
		position = song.position; 
		song.stop(); 
            } 
	}     

	// Switch to Previous Song 
	public function prev():void { 
	    currentIndex--; 
	    if (currentIndex < 0) { 
	        currentIndex = songURLs.length - 1; 
	    }    

	    song.stop(); 
	    position = 0;    

	    // Track if player was already playing, 
	    // paused, or stopped. If stopped or 
	    // paused, still "play" so we can start 
	    // streaming and obtain the id3 info.    

	    var wasStopped:Boolean = stopped; 
	    var wasPaused:Boolean = paused;    

	    playMP3(currentIndex);    

	    if (wasStopped) { 
	    	stop(); 
	    	return; 
	    } 
	    if (wasPaused) { 
		paused = true; 
		position = song.position; 
		song.stop(); 
    	    } 
	} 
    } 
}

The MXML for the custom mp3 player component, SimpleMP3.mxml:

<?xml version="1.0"?> 
<!-- SimpleMP3.mxml --> 
<custom:SuperSimpleMP3Player 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:custom="*"> 
     <mx:Label text="{String(songName)}"/> 
     <mx:ControlBar horizontalAlign="center"> 
      <mx:Spacer width="100%"/> 
      <mx:Button id="prevButton" label="<<" click="prev()"/> 
      <mx:Button id="pauseButton" label="||" click="pause()"/> 
      <mx:Button id="stopButton" label="X" click="stop()"/> 
      <mx:Button id="nextButton" label=">>" click="next()"/> 
      <mx:Spacer width="100%"/> 
    </mx:ControlBar> 
</custom:SuperSimpleMP3Player>

The MXML for container application, SimpleMP3Player.mxml:

<xml version="1.0" encoding="utf-8"?> 
<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:custom="*" 
    layout="vertical" 
  <custom:SimpleMP3 id="myMP3" headerHeight="0"  width="400"/> 
</mx:Application>

4) From the command line I compiled the file:

c:/flex_sdk_2/learning>../bin/mxmlc.exe 
	-use-network=false 
	SimpleMP3Player.as

Note that I had to use the ‘-use-network=false’ directive. This told the compiler that I will not be using the network in my testing so don’t worry about sandbox issues when trying to load the flv from my local drives. Once I decide, if I decided, to deploy this to a website, I will need to recompile my code without this directive.

6) After compilation succeeded, I loaded the swf in the debug Flash Player:

c:/flex_sdk_2/learning>../player/debug/SAFlashPlayer.exe 
	SimpleMP3Player.swf

Success. However, please don’t think of this as the only way of doing or even close to the best way of doing. No best practices used here, like supplying some sort of packaging/namespacing for my custom code and components, just me documenting my learning experience. 😉 I do hope this helps a few other with their own learning experiements and if you know of cleaner solutions, please feel free to leave some feedback in my comments section.

For reference, the source can also be downloaded from http://www.kriggio.com/mp3player/SuperSimpleMP3Player.zip

The following link, which may or may not be available depending if I have to take it down due to bandwidth issues, demonstrates the above code: http://www.kriggio.com/mp3player/mp3.html. Streaming mp3s = lots of bandwidth. 😦

Advertisements

June 19, 2007 - Posted by | ActionScript, flex, Programming, technology

20 Comments »

  1. […] Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2  Via Kriggio […]

    Pingback by Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2 « Flash Enabled - Get Ready With Flash… | June 20, 2007 | Reply

  2. Can I reference your example in book I am writing?

    Comment by Jim Clarke | September 4, 2007 | Reply

  3. Jim,

    Feel free to reference the example. I am just happy to see that some people find my example useful.

    Comment by Kenneth Riggio | September 4, 2007 | Reply

  4. […] “Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2” […]

    Pingback by the rasx() context » Blog Archive » Confronting ActionScript 3 and the Flex SDK | November 13, 2007 | Reply

  5. Thank you for useful info

    Comment by Ride | January 3, 2008 | Reply

  6. can anyone tell me the link of
    mp3 player using action script 2.0…

    Comment by renu | January 10, 2008 | Reply

  7. is this AS3? i guess..
    how come song.position does not work?

    Comment by Iuretz | January 26, 2008 | Reply

  8. Ok I’m a n00b at this so please no disparaging remarks. Where do you put the MP3 files to get them picked up with this code?

    Comment by molesdad | March 12, 2008 | Reply

  9. nice thanks for sharing

    Comment by Turn fun | April 9, 2008 | Reply

  10. That’s very interesting!

    Comment by la bella | May 2, 2008 | Reply

  11. Somehow i missed the point. Probably lost in translation 🙂 Anyway … nice blog to visit.

    cheers, Egocentrically

    Comment by Egocentrically | June 23, 2008 | Reply

  12. nice tut. but can u tell me how i can fine the value of the final position. I mean when you pause the audio, a value is stored in the variable position. But that value does mean any sense to me. How can I find the value of the final position????

    Comment by Hanush | December 5, 2008 | Reply

  13. Nice example, but I prefer using only actionscript in small projects. Flex produces large swf files (empty mxml generates ~140kB of result code).

    Comment by Adam | December 27, 2008 | Reply

  14. In fact, it is within the price range that is estimated for
    other impressive tablets that can be found in the market.

    There are many new applications available for you
    to download within the market. if you’re under 120 lbs, unless you’re really short you are NOT overweight.

    Comment by tommy bookmarks | May 14, 2013 | Reply

  15. POINT BLANK THEIR HAS TO BE SOME KIND OF DISCLIPINE IN ORDER TO LIVE A HEALTHY LIFESTYLE
    AND MAINTAIN A GOOD APPEARANCE. And with good reason because sometimes
    running an app on the big screen is nothing short of magical.
    if you’re under 120 lbs, unless you’re really short you are NOT overweight.

    Comment by morethanabook.ca | May 15, 2013 | Reply

  16. I really like what you guys are up too. This sort of clever work and coverage!
    Keep up the terrific works guys I’ve included you guys to my blogroll.

    Comment by Matt Bushs Local Marketing Business System | May 16, 2013 | Reply

  17. The experience: I had to have someone come in to set up my computer,
    . Here are 10 easy steps you can take to lower your exposure
    to tree pollen and other spring allergens, and keep allergy symptoms under
    control. Usually take into account the following prior to cleaning your floors:.

    Comment by eurorail price | May 16, 2013 | Reply

  18. The device is also very light, weighing slightly less than 3 oz.
    Whereas some cameras will auto-focus while doing video, others do not
    which is something else to consider. s r CMOS sensor, BIONZ impression processor chip
    in addition to a Sony Grams contact with powerful (10x optical move, 25-250 mm range) wide-angel
    mega-zoom (26 mm) help in choosing stunning golf swings quite possibly with
    low-light circumstances.

    Comment by dlp projectors | May 16, 2013 | Reply

  19. There are many people moving on with the art of photography in
    the right manner. Once decided on the things to bring, start packing.
    Whenever you rent a book from them, they plant a tree to
    show the benefits of renting books.

    Comment by visa credit card low interest | May 21, 2013 | Reply

  20. […] Via Kriggio […]

    Pingback by Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2 | Biitlog | February 27, 2017 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: