You are Here:Home>>Old Posts>>Tutorial | Create a AS3 / Flash 9 MP3 Player with spectrum display

Tutorial | Create a AS3 / Flash 9 MP3 Player with spectrum display

By | 2008-05-28T22:32:30+00:00 May 28, 2008|Old Posts|

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.
// 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 Nünlist is currentyl 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.

About the Author:

A father, a husband and a geek... Carlos was the founder of projects like The Tech Labs and Flash Enabled Blog. He is the founder of TekTuts He is passionate about technologies. Their main skills are in analytics, transport & logistics, business administration. He also writes about programming resources, trends, strategy and web development.

8 Comments

  1. Hugh June 24, 2008 at 10:00 am - Reply

    Great tutorial !
    thx you so much for putting it there ,but i do have a question , hopefully u can able to solve my problem , anyway i want to repeat the music , is it anyway to do that ?

  2. cliff June 26, 2008 at 9:29 pm - Reply

    Correct me if i am wrong but there seems to be a fundamental error here regarding your spectrum, it seems u have the right channel constantly in oposition with the left channel. In fact in ur code u make a cut at 256, but the byteArray different from a usual Array returns in each of your for loops the entire spectrum left + right. So i will point in the right direction, one way is to control directly the position in the bit array something like i*16, with i from 0 to 63 (for left)and then 64 to 128 (for right), so something like myBytes.position = i * 16; and then the usual myBytes.readFloat() Hope this helps and please let me know if i am not talking complete bullsh@”’t, lol.

  3. flash design brighton July 7, 2008 at 3:25 pm - Reply

    awesome use of this new functionality, really useful example thanks very much!

  4. sanchaita July 24, 2008 at 6:06 am - Reply

    it will be help full for creating a mp3 player but it should be include more option and it will be create if we connect it with database

  5. brittany January 17, 2009 at 8:54 pm - Reply

    what are you trying to say

  6. fraenk February 9, 2009 at 10:09 pm - Reply

    neat tutorial!!

    everything works fine until the player is displayed inside a browser? cant’s think of any explanations but inside the browser the spectrum analyzis is not visible anymore. launching the swf directly inside the flashplayer works fine though?!?

  7. Thomas April 13, 2009 at 4:10 am - Reply

    fraenk maybe upgrade to the latest version of flash for the browser you are using?

  8. Michael July 25, 2009 at 8:19 am - Reply

    what a mess..Look at all those crazy functions. If you use this tutorial, replace all those crazy functions with this structure instead:

    stop_btn.addEventListener(MouseEvent.MOUSE_DOWN, managePlayerControls);
    play_btn.addEventListener(MouseEvent.MOUSE_DOWN, managePlayerControls);
    pause_btn.addEventListener(MouseEvent.MOUSE_DOWN, managePlayerControls);
    next_btn.addEventListener(MouseEvent.MOUSE_DOWN, managePlayerControls);
    prev_btn.addEventListener(MouseEvent.MOUSE_DOWN, managePlayerControls);

    public function managePlayerControls (event:MouseEvent):void{
    switch(event.currentTarget){
    case stop_btn :
    // stop button code
    break;
    case play_btn :
    // play button code
    break;
    case pause_btn :
    // pause button code
    break;
    case next_btn :
    // next button code
    break;
    case prev_btn :
    // prev button code
    break;
    }
    }

    etc….

Leave a Reply