RSS

Create a AS3 / Flash 9 MP3 Player with spectrum display

Wed, May 28, 2008

Audio & Video, Flash, Interfaces, Tutorials

Create a AS3 / Flash 9 MP3 Player with spectrum display

In this tutorial, we’re going to build a Flash mp3 player with a spectrum analyzer written in AS3. We’ll focus on the spectrum analyzer and build just the basic functionality for the player itself.

Actionscript 3 has a new class called SoundMixer which gives you global sound control in the SWF file. It comes with the computeSpectrum method that takes a snapshot of the current sound wave and places it into the specified ByteArray object. The values are formatted as floating-point values, in the range -1.0 to 1.0. There are in total 512 values. Half of them for the right and left channel.

With these values you can easily create a visual spectrum. Let’s take a closer look at our renderSpectrum function, which is automatically called, when Flash enters a new frame.

First of all, we set a reference to the spectrum graphics:

function renderSpectrum(e:Event):void
{
var g:Graphics = this.mcMp3Player.spectrum.graphics;

Next, we compute the spectrum in the byte array “sndBytes”:

SoundMixer.computeSpectrum(sndBytes);

And then comes the most important part, visualizing the spectrum that is. We clear all the graphics and set a new line style and fill and move our drawing pointer to the middle left position.

Next, we create a number “n” which will contain the multiplied number from the maximum height of the spectrum and the current float number.

To create the curves, we iterate 256 times (which represents the left channel values) and read the current  float numbers from the byte array. Note that reading a value from a byte array will automatically set the pointer position to the next value.

As mentioned before, we multiply the float number with the maximum height and set it to “n”. In our case the value will be between 75 and -75 depending on what values we get from the byte array. To draw the line we use “i * 2″ for the x-coordinate and “SPECTRUM_HEIGHT – n” for the y-coordinate. This will result in a nice wave shape. We only need to set the end point for the line and end the fill instruction.

For the right channel it’s the same procedure, except that we take the last 256 values from the byte array.

g.clear();
g.lineStyle(0, SPECTRUM_LEFT_LINE_COLOR);
g.beginFill(SPECTRUM_LEFT_FILL_COLOR, SPECTRUM_LEFT_FILL_ALPHA);
g.moveTo(0, SPECTRUM_HEIGHT);
var n:Number = 0;
for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
n = (sndBytes.readFloat() * SPECTRUM_HEIGHT);
g.lineTo(i * 2, SPECTRUM_HEIGHT - n);
}
g.lineTo(CHANNEL_LENGTH * 2, SPECTRUM_HEIGHT);
g.endFill();

As you can see, it’s very easy to create a nice little spectrum. There are many other amazing spectrum analyzer out there which you should check out.

Here is the full code of this mp3 player, with the constants and vars, where you set the animation parameters:

// spectrum constants
const SPECTRUM_HEIGHT:int                 = 75;
const CHANNEL_LENGTH:int                 = 256;
const SPECTRUM_LEFT_FILL_COLOR:uint        = 0x5FDEFE;
const SPECTRUM_LEFT_FILL_ALPHA:Number    = 0.5;
const SPECTRUM_LEFT_LINE_COLOR:uint        = 0x013643;
const SPECTRUM_RIGHT_FILL_COLOR:uint    = 0xBFF075;
const SPECTRUM_RIGHT_FILL_ALPHA:Number    = 0.5;
const SPECTRUM_RIGHT_LINE_COLOR:uint    = 0x4A730D;
// vars
var sndObject:Sound                = new Sound();
var chaObject:SoundChannel        = new SoundChannel() ;
var sndTransform:SoundTransform    = new SoundTransform();
var reqObject:URLRequest         = new URLRequest("so-deep.ram2000.mp3");
var sndBytes:ByteArray            = new ByteArray();
var intPosition:int             = 0;
var bolStop:Boolean                = true;
function initMP3Player():void {
// set event listeners
addEventListener(Event.ENTER_FRAME, renderSpectrum);
addEventListener(Event.ENTER_FRAME, calcProgress);
this.mcMp3Player.btnStop.addEventListener(MouseEvent.CLICK, stopPlayback);
this.mcMp3Player.btnPause.addEventListener(MouseEvent.CLICK, pausePlayback);
this.mcMp3Player.btnPlay.addEventListener(MouseEvent.CLICK, startPlayback);
this.mcMp3Player.btnMute.addEventListener(MouseEvent.CLICK, mutePlayback);
this.mcMp3Player.btnUnmute.addEventListener(MouseEvent.CLICK, unmutePlayback);
this.mcMp3Player.progress.addEventListener(MouseEvent.CLICK, setNewProgress);
// use hand cursor for progress bar
this.mcMp3Player.progress.buttonMode = true;
this.mcMp3Player.btnPause.visible    = false;
this.mcMp3Player.btnUnmute.visible    = false;
}
function stopPlayback(e:MouseEvent):void {
chaObject.stop();
sndObject = new Sound();
bolStop = true;
intPosition = 0;
this.mcMp3Player.btnPlay.visible    = true;
this.mcMp3Player.btnPause.visible    = false;
}
function pausePlayback(e:MouseEvent):void {
this.mcMp3Player.btnPlay.visible    = true;
this.mcMp3Player.btnPause.visible    = false;
playSound(false);
}
function startPlayback(e:MouseEvent):void {
this.mcMp3Player.btnPlay.visible    = false;
this.mcMp3Player.btnPause.visible    = true;
playSound();
}
function mutePlayback(e:MouseEvent):void {
this.mcMp3Player.btnMute.visible    = false;
this.mcMp3Player.btnUnmute.visible    = true;
setVolume(0);
}
function unmutePlayback(e:MouseEvent):void {
this.mcMp3Player.btnMute.visible    = true;
this.mcMp3Player.btnUnmute.visible    = false;
setVolume(1);
}
function setNewProgress(e:MouseEvent):void {
var p:int = sndObject.length * e.currentTarget.mouseX / 220;
chaObject.stop();
chaObject = sndObject.play(p);
this.mcMp3Player.btnPlay.visible    = false;
this.mcMp3Player.btnPause.visible    = true;
}
function playSound(bolPlay:Boolean = true):void {
if(bolPlay) {
if(bolStop) {
// load mp3 file if playback has been stopped
sndObject.load(reqObject);
bolStop = false;
} else {
intPosition = chaObject.position;
}
chaObject = sndObject.play(intPosition);
} else {
chaObject.stop();
}
}
function setVolume(intVolume:int = 1):void {
sndTransform.volume = intVolume;
chaObject.soundTransform = sndTransform;
}
function calcProgress(e:Event):void {
var p:MovieClip = this.mcMp3Player.progress.mcProgressFill;
var w:int        = Math.round( 220 * chaObject.position / sndObject.length);
p.width         = w;
}
function renderSpectrum(e:Event):void
{
// set a reference to the spectrum graphics
var g:Graphics = this.mcMp3Player.spectrum.graphics;
// compute spectrum in byte array sndBytes
SoundMixer.computeSpectrum(sndBytes);
/*
*    LEFT CHANNEL
*/
g.clear();
g.lineStyle(0, SPECTRUM_LEFT_LINE_COLOR);
g.beginFill(SPECTRUM_LEFT_FILL_COLOR, SPECTRUM_LEFT_FILL_ALPHA);
g.moveTo(0, SPECTRUM_HEIGHT);
var n:Number = 0;
for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
n = (sndBytes.readFloat() * SPECTRUM_HEIGHT);
g.lineTo(i * 2, SPECTRUM_HEIGHT - n);
}
g.lineTo(CHANNEL_LENGTH * 2, SPECTRUM_HEIGHT);

g.endFill();
/*
*    RIGHT CHANNEL
*/
g.lineStyle(0, SPECTRUM_RIGHT_LINE_COLOR);
g.beginFill(SPECTRUM_RIGHT_FILL_COLOR, SPECTRUM_RIGHT_FILL_ALPHA);
g.moveTo(CHANNEL_LENGTH * 2, SPECTRUM_HEIGHT);
for (i = CHANNEL_LENGTH; i > 0; i--) {
n = (sndBytes.readFloat() * SPECTRUM_HEIGHT);
g.lineTo(i * 2, SPECTRUM_HEIGHT - n);
}
g.lineTo(0, SPECTRUM_HEIGHT);
g.endFill();
}
initMP3Player();

So, we’ve already reached the end of our lesson and we hope, that you enjoyed it!

Be sure to check back soon as we’ll take the spectrum analyzer to 3d!

Download Support files

 

About the Author


Rafael Nuenlist - who has written 7 posts on Flash Platform and ActionScript Tutorials.

Rafael Nünlist is currently working at orange8 as a Richmedia Developer. He will complete his apprenticeship with a swiss federal vocational diploma in information technology this summer. His strengths are Flash, Flex, Actionscript, Php/MySQL and AIR. He is also a member of the dreaminginflash team.

29 Comments For This Post

  1. Maicon Says:

    buffer and loading is possible?

  2. Rafael Nünlist Says:

    @Maicon: Yes, both are possible. There is a isBuffering property in the sound class and a event handler for the progress event. More on livedocs (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/index.html?flash/media/Sound.html&flash/media/class-list.html)

  3. Gil Yellows Says:

    i downloaded the file, but when i try to imcluide it importing it to a movie clip, it doesn´t work, also failed with loadmovienum, is there a way to make it work on this circumstances?. Thank you.

  4. Manuel Says:

    Thank you!!!!!!!!!!

  5. licius Says:

    nice, it works.
    thks very much.

  6. Kevin C Says:

    where do I put the mp3 file? im new at this..

  7. jhay Says:

    is it possible to add many songs?

  8. Vishal Chander Says:

    hey we have some issues . the play line exceeds the border.. hope u have not seen…thanks…any sort of help mail me…
    thank you

  9. Rafael Nünlist Says:

    @Gil Yellows: LoadMovieNum is for AS2 and not AS3. You can load the SWF by using the Loader class for AS3.

    @Kevin C: You can put your mp3 wherever you want on your webserver. Then you just add the absolute or relative path in the swf.

    @jhay: Yeah, you could make an array with the path to many songs and use it as a playlist. See the extended video player for more info ;)

    @Vishal Chander: There might be the wrong width in the code since the fla has been redesigned. Just do the following: Measure the width of the progressbar and put the pixel count here:

    function setNewProgress(e:MouseEvent):void {
    var p:int = sndObject.length * e.currentTarget.mouseX / 220; // replace 220 with the measured width
    chaObject.stop();
    chaObject = sndObject.play(p);
    this.mcMp3Player.btnPlay.visible = false;
    this.mcMp3Player.btnPause.visible = true;
    }

    And here:
    function calcProgress(e:Event):void {
    var p:MovieClip = this.mcMp3Player.progress.mcProgressFill;
    var w:int = Math.round( 220 * chaObject.position / sndObject.length); // replace 220 with the measured width
    p.width = w;
    }

  10. Erik Says:

    Thank you Rafael.

    I’m happy with it on http://www.beatgate.com/mix/

    Respect for your work.

  11. Siobhan Says:

    Hi,

    I tried to link it to the mp3 i want to use. I put the path file into
    var reqObject= new URLRequest(“C:\Users\siobhan\Uni\project\brendan photos\audio\Indica”);

    I am getting an error;
    Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
    at mp3player_fla::MainTimeline/frame1()

    please help??

  12. andikurnia Says:

    thx for the tutorial…..

  13. Jan Says:

    I like this. Very fun, but can I control the volume? It seems like I should be able to on the right side.

    Thanks.

  14. Rafael Kunkel Says:

    First of all thanks for your nice work,ammm i was wondering a way to make this player play automatically without having to select the play button, thanks , and your credits will be for sure in the webpage in which ill implement it.
    Thanks a lot!!!

  15. fabio Says:

    Hi Rafael. Tanks for the great code! Was a big help for me! But now I have a doubt. If I need to start the movie clip with the song playing how should I do? I tryed some things but withou success.
    Hugs.

  16. Marcos Says:

    Great player but what must i do to make it stream of a live radio feed. In this line what must i change var reqObject:URLRequest = new URLRequest(“livefeedurl”); i can make it work locally from the live feed but when i put player to server it always says on bottom bar of explore ” getting data from URL. Am i putting the live feed address wrong var reqObject:URLRequest = new URLRequest(“http:99.99.99.99:8000″);

  17. Dean Hayden Says:

    This is fantastic, might be missing something obvious but how can you get the mp3 to start automatically?

  18. fogpuddle Says:

    Thanks Rafael for all your great tutorials. I’m new to AS3 and came upon this site a couple of months back and is now on my fav’s list. Anyway, I’m now building an MP3 player using this site as a reference source. One thing I want to have on the mp3 player is a space to store all the songs that are in the XML file where users can click on and play. Right now, user’s aren’t able to see what songs are coming next or go directly to a song they like. Do you have a function available that would allow me to do that? Thanks

  19. Peter Says:

    I added the ability to set the mp3 file and add a title to a dynamic text field using flashvars (or pull the info from the URL link itself), but for some reason I can’t get it to read the loaded sound file’s length and output a total time and elapsed time counter. Any thoughts?

    Here’s what I have so far (doesn’t work):

    // Get full time from sndObject, then break into minutes, secs, etc
    var tallytime = (sndObject.length/1000);
    var totalmins:Number = Math.floor(tallytime /60);
    var totalsecs = Math.floor (tallytime) % 60;
    if (totalsecs < 10){
    totalsecs = “0″ + totalsecs;
    }
    this.mcMp3Player.displayFullTime.text = ( ” ” + totalmins + “:” + totalsecs);
    trace (“totalmins: ” + totalmins);
    trace (“totalsecs: ” + totalsecs);
    // End get Full time
    // Get playing time from chaObject and break up
    var totalSeconds:Number = chaObject.position/1000;
    var minutes:Number = Math.floor(totalSeconds /60);
    var seconds = Math.floor (totalSeconds) % 60;
    if (seconds < 10){
    seconds = “0″ + seconds;
    }
    this.mcMp3Player.displayTime.text = (” ” + minutes + “:” + seconds);
    // End get playing time

  20. Jasen Burkett Says:

    I was wondering…is there anyway to simply add the following..

    a listbox component so that people can select a song from a playlist?

    thanks
    Jasen

  21. Jasen Says:

    Very serious question.

    I have a list box that is being populated from xml file.
    I need to know how to make the player look to that for its
    sound object.

    I have tried to give it — lb.selectedItem.data;
    I have tried to give it — lb.getItemAt(0).data;

    and others but with nothing working.

    I only really need the stop, and pause function, but for right now
    I just need the first item in the list box to play automatically,
    then if the user clicks something in the list box it would change
    to that.

    Any help would be great!!!!!

    thanks

  22. JS Says:

    Why don`t you have a demo for this?

  23. joemax Says:

    How I should add the bar of the sound playing draggable ?

  24. Zac Says:

    hey, i’m designing a website and i need this mp3 playe but i need it to work with an xml playlist i have already written.
    how could i go about doing this???

  25. Carlos Says:

    How to make it auto-play? Please somebody tell me;]

  26. biohazard Says:

    hi …is poseble a spectrum for video…..the sound of the video??…i need this…plase ..someone help…..thnx…

  27. andybrandy Says:

    thx for the code! still useful

  28. Sandra Says:

    I want an mp3 player like this one here http:/www.invisioner.com . Can someone tell me where can i find something like it? Thanks in advance

  29. Scott Says:

    This is really excellent! May I use this code in my project?

10 Trackbacks For This Post

  1. Tutorials | Great How-to Articles on Create Audio Spectrums with AS3 « Flash Enabled Blog Says:

    [...] Read Tutorial [...]

  2. Create a AS3 MP3 Player with papervision3d spectrum display | The Tech Labs Says:

    [...] If you’re not comfortable with the SoundMixer.computeSpectrum method then you should read the previous tutorial. So, let’s start with the [...]

  3. Flash Tutorials | Great How-to Articles on Create Audio Spectrums with AS3 | Lemlinh.com Says:

    [...] Read Tutorial [...]

  4. Create a AS3 MP3 Player with papervision3d spectrum display - Blue Box Sols Says:

    [...] If you’re not comfortable with the SoundMixer.computeSpectrum method then you should read the previous tutorial. So, let’s start with the [...]

  5. Create a AS3 / Flash 9 MP3 Player with spectrum display - The Tech … Says:

    [...] Read more: Create a AS3 / Flash 9 MP3 Player with spectrum display – The Tech … [...]

  6. Create a AS3 MP3 Player with papervision3d spectrum display « NICE TUTORIALS Says:

    [...] If you’re not comfortable with the SoundMixer.computeSpectrum method then you should read the previous tutorial. So, let’s start with the fun.    read morevisite [...]

  7. Fresh News 2.0 Wordpress Theme | Adobe roundup Says:

    [...] See for yourself.. [...]

  8. 6 Flash Mp3 Player | Lemlinh.com Says:

    [...] See for yourself.. [...]

  9. Best collection of Flash MP3 Players. best to use. | guidesigner.net Says:

    [...] See for yourself.. [...]

  10. Best collection of Flash MP3 Players. best to use. | Web Design GroundBreak Says:

    [...] See for yourself.. [...]

Leave a Reply