Search Flex Components Free

Custom Search
Showing posts with label Flex Vs Action Script. Show all posts
Showing posts with label Flex Vs Action Script. Show all posts

January 23, 2008

Specifying certain unicode-ranges for embedded fonts

you want to embed the numbers 0-9, you would click on “0″ and note it’s Unicode value (U+0030), then click on “9″ and do the same (U+0039). Now, in your Flex application, you would specify this range in the @font-family style block like so:




<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

verticalAlign="middle"

backgroundColor="white">



<mx:Script>

<![CDATA[

/* Import all the easing classes so its

easier to switch between them on the

fly without tweaking import statements. */

import mx.effects.easing.*;

]]>

</mx:Script>



<mx:Style>

@font-face {

src: url('assets/base02.ttf');

font-family: Base02;

unicode-range:

U+0054-U+0054, /* T */

U+0061-U+007A, /* a-z */

U+002E-U+002E; /* . (period) */

}



.MyEmbeddedFont {

font-family: Base02;

font-size: 14px;

}

</mx:Style>



<!-- Set zoom effect for 2.5 seconds (2500 milliseconds) and use the Elastic.easeOut easing method. -->

<mx:Zoom id="zoom" duration="2500" easingFunction="Elastic.easeOut" target="{embeddedText}" />



<!-- Use advanced font anti-aliasing for the embedded font, set

the rotation to 5 degrees, alpha to 80% and loop the animation. -->

<mx:Text id="embeddedText" text="The quick brown fox jumped over the lazy dog." styleName="MyEmbeddedFont" rotation="5" alpha="0.8" fontAntiAliasType="advanced" creationComplete="zoom.play();" effectEnd="zoom.play()" />

</mx:Application>

December 27, 2007

Serrano Image Viewer built with Flex Builder 3 and AIR

Here is a simplistic image viewing application named “Serrano” built with Flex Builder 3. One main plus for the app is the ability to view SWF’s in the users local system. The app was originally created in Flex Builder 2 and then ported to FB3. This is very much an alpha release or even a prototype for now. The user experience still needs to be solidified and there are a few features that need to be built out, like thumbnail view, etc.
At the moment Serrano is having some trouble displaying images on Mac’s (or at least the one my friend Joshua Behshad tested with). So I need to get that kink worked out. There are a few other issues, but I think the app is presenting the basic proof of concept for now.
Please take a look and let me know what you think. As I mentioned there is still a bit of work left so consider this somewhat of a preview.
One thing to mention is that the port to Flex Builder 3 was painless. Pretty much copy and paste unlike the SQLite app that I had built which took quite a bit of work to get ported. Just an FYI for other AIR developers out there.
Download Serrano

AS3 Using XML data and parse it to a List Component - FLASH CS3

Using AS3 to load XML data it's quite different than using AS2. In this tutorial I will explain to you, how we can load an external XML data, bring it to the fla file, and parse it to a List component. Using your notepad or similar program, make a simple XML file like the above example.

<?xml version=”1.0″ encoding=”iso-8859-1″?>

<news>
<item date = “ 01/01/2007 “ >
<title> news1 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao1 </pic>
</item>
<item date = “ 02/02/2007 “ >
<title> news2 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao2 </pic>
</item>
<item date = “ 03/03/2007 “ >
<title> news3 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao3 </pic>
</item>
<item date = “ 04/04/2007 “ >
<title> news4 </title>
<description> Lorem ipsum elitrgh dolor sit amet, consectetuer adipiscing elit. Maecenas vitae nisi. </description>
<pic> japao4 </pic>
</item> </news>

Save it at the same directory as your fla file, naming it as news.xml . Now, the first step to load the xml file, we use the following code:


var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

xmlLoader.load(new URLRequest(”news.xml”));

As you are using AS3, every time we define a variable, we must identify, which kind of variable is it. In the above code we say that the variable xmlLoader belongs to the URLLoader class ( xmlLoader:URLLoader ) , and the xmlData is the type XML ( xmlData:XML ). When the data is loaded, we must say to the code “where to go”. It's an event, so xmlLoader.addEventListener(Event.COMPLETE, LoadXML); , it's the same as saying that when the xml data was completely loaded, then calls the function LoadXML. Now drag a List component into stage, and name it as my_lst .

The following code will define which data we want to show on the List component, as also parse into it.

function LoadXML(e:Event):void {

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

ParseNews(xmlData);

}

function ParseNews(newsXML:XML):void {

var newsList:XMLList = newsXML.item.title;

f or each (var newsTitle:XML in newsList) {

my_lst.addItem({label:newsTitle, data:newsTitle});

}

}

Run your movie.

Tutorial - Animating Dynamic MovieClips in AS3

It is fairly straightforward to animate in Flash using the timeline. With a little knowledge of programming, you can even animate movie clips that exist on your stage. What is more tricky, though, is animating movie clips that neither use the timeline nor exist on the stage. These movie clips exist solely in your Library, and this tutorial will cover how to use code to animate them.
For example, click around the following blue rectangle to see circles fade in and fade out at the location of your click:
if (AC_FL_RunContent == 0) { alert(”This page requires AC_RunActiveContent.js.”); } else { AC_FL_RunContent( ‘codebase’, ‘http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0′, ‘width’, ‘350′, ‘height’, ‘250′, ’src’, ‘dynamicMC_animation’, ‘quality’, ‘high’, ‘pluginspage’, ‘http://www.macromedia.com/go/getflashplayer’, ‘align’, ‘middle’, ‘play’, ‘true’, ‘loop’, ‘true’, ’scale’, ’showall’, ‘wmode’, ‘window’, ‘devicefont’, ‘false’, ‘id’, ‘dynamicMC_animation’, ‘bgcolor’, ‘#ffffff’, ‘name’, ‘dynamicMC_animation’, ‘menu’, ‘true’, ‘allowFullScreen’, ‘false’, ‘allowScriptAccess’,’sameDomain’, ‘movie’, ’swf/dynamicMC_animation’, ’salign’, ” ); //end AC code }
The circles are added to the stage and animated only when your mouse is clicked, and in this tutorial, you will learn how to animate content drawn and stored in your library.
Let’s Get StartedFirst, you will need to create a movie clip that will be loaded dynamically. For this article, simply create a solid blue circle movie clip and, in the Library, give it the class name BlueCircle. If you are not sure how to do that, the following instructions will help you out.
If you already know how to do create a circle stored in the Library with the class name BlueCircle, skip on over to the next page where you’ll see the code.
Creating the BlueCircle MovieClip:The following instructions explain how to setup your movie and specify the blue circle that will be loaded dynamically.
First, create a new animation in Flash CS3. From the Properties panel, click the button next to the Size text and set the animation’s width and height to 300 pixels by 200 pixels respectively:
[ set your animation’s width/height to 300 by 200 ]
Now that our stage’s width and height have been setup just the way we want, let’s draw a circle. Using the Circle tool, draw a circle with a blue solid-fill color:
[ draw a blue, solid, filled circle ]
Make sure your circle has been selected and press F8 or go to Modify Convert to Symbol. The Convert to Symbol window will appear. For name, enter circle and make sure the Movie Clip option has been selected:
[ give your symbol the name circle and make sure it is also set to be a movie clip ]
Do not hit OK just yet. Let’s make some more modifications.
From the same Convert to Symbol window, find the area marked Linkage. If you do not see the Linkage area, press the Advanced button to display it. Check the box that says Export for Actionscript. A few lines above that, in the Class field, replace whatever text is displayed (probably circle) with the text BlueCircle:
[ check ‘Export for ActionScript and enter BlueCircle for your class ]
The Base class field will automatically be populated for you, but if it hasn’t, make sure to enter flash.display.MovieClip as shown in the above image.
Press OK to close the Convert to Symbol window. After you have pressed OK, you will see your Library display your newly created symbol:
[ your circle in your Library ]
If you do not see your Library, press Ctrl + L to display it.
At this point, your circle movie clip is stored in the Library, and you have a copy of that same clip on your stage right now. Select the blue circle movie clip located on your stage and delete it by pressing the Delete key. You should now have a blank stage with nothing in it.
Ok, you should see a blank stage with your library displaying the circle movie clip with the class name BlueCircle. Right now, nothing is really being done. We’ll change that on the next page when you add the code.

Tutorials - AS3 Tutorials

Here are some nice AS3 tutorials.
http://flashenabled.wordpress.com/2007/05/30/getting-started-with-actionscript-3/
http://flashenabled.wordpress.com/2007/06/06/tutorial-displaying-library-content-in-as-30/
http://flashenabled.wordpress.com/2007/06/05/tutorial-as3-xml-sockets/
http://flashenabled.wordpress.com/2007/06/05/tutorial-animating-dynamic-movieclips-in-as3/
http://flashenabled.wordpress.com/2007/06/01/tutorial-spectrum-analyzer-with-as3/
http://flashenabled.wordpress.com/2007/05/30/as3-particle-system/
Hope you enjoy it.

FLASH 3D OPEN SOURCE PROJECTS 3D PAPERVISION VS SANDY 3D


Everyone is seeking for an easy and fast way to use 3d inside flash projects. At this time the most sounding 3D projects (open source) are 3D Papervision and Sandy 3D.
Looking to 2 demos, 1 from Sandy 3D and another one from 3D Papervision , i can say that the texture detail of 3D Papervision is higher than on Sandy. However, the rino is not moving, and maybe that’s why it seems to have higher detail. On the other hand, in Sandy 3D, the demo i’ve checked, have motion, one thing that i though could slower the loading rate, or the animation performance, but it didn’t. Load’s faster and don’t consume too many resources, which is 2 nice things to win the race. So, in other words, and to summarize,
- 3D Papervision it have a great texture detail;


Tutorial - Spectrum analyzer with AS3

Introduction:Spectrum analyzer with AS3
I have created music driven animation since Flash 5 and I must say there has not been much progress until just now. I started out by importing sounds directly to the timeline and made keyframes according to the amplitude shown, a slow and painful method. Soon people created different approaches, some better than others, but the one I have used the most is SwiftMP3 from http://www.swift-tools.net/. It started as a free script that could be used either on a server for real-time conversion or from a dos prompt.
Now, with the release of AS3, we can use existing classes to load external mp3 files and read the spectrum variables in runtime! In this tutorial I will show how it is done.
1: SoundMixer class
The SoundMixer class is a part of the flash.media package. It contains classes for manipulation of both video and sound as well as classes for working with media in Flash Communication Server.
The SoundMixer class inherits from Object and contains properties and methods for controlling embedded streaming sounds but it can not be used together with Sound objects created with AS.
Methods defined in the SoundMixer class:
areSoundsInaccessible():Boolean//Determines whether any sounds are not accessible due to security restrictions.
computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void//Takes a snapshot of the current sound wave and places it into the specified ByteArray object.
stopAll():void//Stops all sounds currently playing.
Methods inherited from the Object class:
hasOwnProperty(name:String):Boolean//Indicates whether an object has a specified property defined.
isPrototypeOf(theClass:Object):Boolean//Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
propertyIsEnumerable(name:String):Boolean//Indicates whether the specified property exists and is enumerable.
setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void//Sets the availability of a dynamic property for loop operations.
toString():String//Returns the string representation of the specified object.
valueOf():Object//Returns the primitive value of the specified object.
Read more at http://livedocs.macromedia.com/flex/2/langref/flash/media/SoundMixer.html
2: computeSpectrum method
Since this tutorial is about analyzing spectrums and music driven animation we will put our main focus on the computeSpectrum method:
public static function computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void
Every time the computeSpectrum method is called it creates a copy of the current wave and stores the data as normalized floating-points between -1 and 1 in the ByteArray (outputArray). If the sound is not running the floating.points get the value zero. The ByteArray has a fixed size of 512 where the first 256 values represent the left channel and the last 256 represent the right.
The FFTMode variable can by set to either true or false determining whether a Fast Fourier transform is performed before the sound wave data is saved. Setting this to true will create a frequency spectrum where low frequencies are shown to the left and high to the right. This is pretty much standard on music players these days, like Winamp for example.
“The Fourier transform is an integral transform that re-expresses a function in terms of sinusoidal basis functions, i.e. as a sum or integral of sinusoidal functions multiplied by some coefficients (”amplitudes”).” http://en.wikipedia.org/wiki/Fourier_transformation
The last variable, stretchFactor, is an integer that determines the sampling rate of the sound. 0 samples the sound at 44 KHz and incrementing the variable with one halves the sampling rate (1 = 22KHz, 2 = 11KHz).
Unfortunately you can not use this method together with sound streamed by the Flash Media Server and its Real Time Messaging Protocol.
3: Load an mp3
Before we can do anything we have to load some music and make it play. Start by opening a new document in Flash 9. In the first frame, we create a Sound object called “mySound”:
var mySound:Sound = new Sound();
Next we load an mp3 file into the Sound object and tell it to play:
mySound.load(new URLRequest(”track.mp3″));mySound.play();
This is the only code we need to play an mp3 file, simple enough!
4: Read and display the spectrum
Now when we have the music playing we will continue by creating a method to calculate the spectrum of the music. First we to create a ByteArray to hold the raw data we will get from the computeSpectrum method. We will simply call this “myByteArray”:
var myByteArray:ByteArray = new ByteArray();
Next we create a function called readSpectrum:
function readSpectrum(event:Event){
SoundMixer.computeSpectrum(myByteArray, false, 0);
graphics.clear();
for(var i = 0; i < 8 =" 32).">c°Tracing myByteArray: <ó€ Tracing myByteArray without readFloat() and FFTMode set to true: Tracing myByteArray: ?P=Þ?@vÊ?dS³?b *?TÌ ?ÄD>ÿ n>´>‡©©? §<–`Tracing myByteArray: ?>à?(Á²?†À?u¼q?Rè/>Œܪa¯Tracing myByteArray: ?@l?V “?e?8 ?C3œ>Ûy•>Ü9í= ™ >—ÚÎ>y2Tracing myByteArray: ?L ?:EÞ?‡‚Í?O˜K?^ÿo>Žã?’±Á>F>>â~Õ>òô=øƒTracing myByteArray: >¦Ýj?.NN?] ‘>þXK? Tracing myByteArray with readFloat() and FFTMode set to false:
Tracing myByteArray.readFloat(): 0.02313232421875Tracing myByteArray.readFloat(): 0.10894775390625Tracing myByteArray.readFloat(): -0.16021728515625Tracing myByteArray.readFloat(): -0.028045654296875Tracing myByteArray.readFloat(): -0.053314208984375
Tracing myByteArray with readFloat() and FFTMode set to true:
Tracing myByteArray.readFloat(): 0.055859118700027466Tracing myByteArray.readFloat(): 0.5461686849594116Tracing myByteArray.readFloat(): 0.05429217591881752Tracing myByteArray.readFloat(): 0.21418170630931854Tracing myByteArray.readFloat(): 0.44413191080093384
The drawSpectrum method is what will draw our spectrum bars. The floating-point number passed on from the readSpectrum method is multiplied with 500 to get a visible difference and then we use a simple drawRect function to draw the graphics.
function drawSpectrum(myReadFloat:Number, myIteration:Number){
var myNumber:Number = myReadFloat * 500;
graphics.lineStyle(1, 0×000000);graphics.beginFill(0xffffff);graphics.drawRect((16 * (myIteration / 8)) +19, 250, 16, -(myNumber / 5));
}
Finally we add an eventlistener that will call readSpectrum on enterframe:
this.addEventListener(Event.ENTER_FRAME, readSpectrum);
This is everything! The code above should provide you with something like this:(Click button to start the music)
5: More examples
Here I used the exact same code as above but set the FFTMode to true and added a blur filter:
var filter:BitmapFilter = new BlurFilter(15, 15, BitmapFilterQuality.HIGH);var myFilters:Array = new Array();myFilters.push(filter);filters = myFilters;(Click button to start the music)
The next one is a little more complex with lines drawn to each peak instead of just using bars:(Click button to start the music)
The code actually is not very complicated, I only changed the two functions to this:
function readSpectrum(event:Event){
graphics.clear();
SoundMixer.computeSpectrum(myByteArray, false, 0);
var myArray:Array = new Array;
for(var i = 0; i < 256; i += 8){
myArray.push(myByteArray.readFloat());
}
drawSpectrum(myArray);
}
function drawSpectrum(myFloatArray:Array){
graphics.lineStyle(5, 0×000000);
for(i = 1; i < myFloatArray.length; i++){
if(i == 1){
graphics.moveTo(20, 0);graphics.lineTo((i+2) * 16, myFloatArray[i+1] * 60);
}else{
graphics.moveTo((i+1) * 16, myFloatArray[i] * 60);graphics.lineTo((i+2) * 16, myFloatArray[i+1] * 60);
}
}
}

AS3 Mouse Events and Mouse Related User Actions

Flash is great for monitoring all actions by a user from what they type to what their mouse is doing and for how long. We have many tracking systems that rely on script in Flash and HTML when not using flash that can detect user interaction with our applications. Many tracking companies also use this info for hotspot or heat maps to see what your users are messing with.To do all this interaction logging and tracking you need mouse events. Mouse events drive games, applications, cool user controlled interfaces, expected user direction and simplify your application. Understanding all the mouse events possible is important. Here is a list of all the events that are clearly implemented in AS3:CLICK : String = “click” MouseEvent
Used to detect mouse clicks. DOUBLE_CLICK : String = “doubleClick” MouseEvent
Used to detect double clicks.MOUSE_DOWN : String = “mouseDown” MouseEvent
Checks when mouse is pressed down.MOUSE_LEAVE : String = “mouseLeave” Event
Monitors when the mouse leaves the stage. MOUSE_MOVE : String = “mouseMove”
Monitors when the mouse moves.MOUSE_OUT : String = “mouseOut”
Monitors when the mouse moves out of the attached to object of the event.MOUSE_OVER : String = “mouseOver”
Monitors when the mouse moves over the attached to object of the event.MOUSE_UP : String = “mouseUp”
Monitors when the mouse moves up the attached to object of the event from a click.MOUSE_WHEEL : String = “mouseWheel”
Monitors when the mouse wheel moves, detect the positive or negative delta property for distance and direction moved.Wiring up Events in AS3 is easier than its ever been. // attach the event listener to this object, if you want a global event outside
// the current class attach to stage.addEventListener([event],[callback])


this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
// then make the callback
public function onMouseClickEvent(event:Event) {
trace(event);
if(event.buttonDown)
// if primary button down, left mouse button
trace(”left button was down”);
else
trace(”left button was not down”);
}What about right clicks?Well not all mouse equipment has right click so its not always best to implement but for the ones that have right click capabilities and other buttons there is both mouse wheel and right click support in Flash mouse events.To detect right click:In the MouseClick event there is a buttonDown property on the event that returns true if its a left click, false if its any other mouse button. So you could have a menu drop down on a mousewheel click, right mouse click or other mouse button clicks.Detecting right clicks or other mouse clicks is impossible in Flash AS3. I got excited and error in testing and thought the buttonDown helped to determine the button pressed but it only listens to the left click. What about drag over and drag out?The buttonDown property is mainly used for drag over or drag out events (which are not an actual event) but you could do something like:

function onMouseOver(event:MouseEvent):void {
if(event.buttonDown==true) {

// mouse is down and dragged over.
trace(’onDragOver’);
}
}function onMouseOut(event:MouseEvent):void {
if(event.buttonDown==true) {

// mouse is down and dragged over.
trace(’onDragOut’);
}
}


To detect when the mouse leaves the screen:Use the MouseEvent.MOUSE_LEAVE event on your main document class or a class instantiated that assigns this event to the stage. This can be used for high intensity flash sites where performance is preserved when the user is not interacting with certain elements.

More on mouse events and timers shortly. Here’s a sample from the docs:
http://livedocs.adobe.com/flex/2/langref/flash/events/MouseEvent.html#constantSummary

package {
import flash.display.Sprite;
public class MouseEventExample extends Sprite {
private var size:uint = 100;
private var bgColor:uint = 0xFFCC00;

public function MouseEventExample() {

var child:ChildSprite = new ChildSprite();
addChild(child);
}
}
}


import flash.display.Sprite;
import flash.events.MouseEvent;

class ChildSprite extends Sprite {
private var size:uint = 50;
private var overSize:uint = 60;
private var backgroundColor:uint = 0xFFCC00;
private var overColor:uint = 0xCCFF00;
private var downColor:uint = 0×00CCFF;
public function ChildSprite() {
draw(size, size, backgroundColor);
addEventListener(MouseEvent.CLICK, clickHandler);
addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);

addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);

addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);

addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);

addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
}
private function draw(w:uint, h:uint, bgColor:uint):void {
graphics.clear();

graphics.beginFill(bgColor);

graphics.drawRect(0, 0, w, h);
graphics.endFill();
}
private function clickHandler(event:MouseEvent):void {

trace(”clickHandler”);
}
private function doubleClickHandler(event:MouseEvent):void {

trace(”doubleClickHandler”);
}
private function mouseDownHandler(event:MouseEvent):void {

trace(”mouseDownHandler”);
draw(overSize, overSize, downColor);
var sprite:Sprite = Sprite(event.target);
sprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
sprite.startDrag();
}

private function mouseMoveHandler(event:MouseEvent):void {

trace(”mouseMoveHandler”);
event.updateAfterEvent();
}
private function mouseOutHandler(event:MouseEvent):void {
trace(”mouseOutHandler”);
draw(size, size, backgroundColor);
}
private function mouseOverHandler(event:MouseEvent):void {
trace(”mouseOverHandler”);draw(overSize, overSize, overColor);
}

private function mouseWheelHandler(event:MouseEvent):void {
trace(”mouseWheelHandler delta: ” + event.delta);

}

private function mouseUpHandler(event:MouseEvent):void {

trace(”mouseUpHandler”);
var sprite:Sprite = Sprite(event.target);
sprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
sprite.stopDrag();

draw(overSize, overSize, overColor);
}

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.



Related Flex Tutorials