Displaying sound data using the SoundMixer.computeSpectrum() method

by Peter deHaan on August 16, 2007

in ActionScript, ByteArray, SoundMixer

The following example looks at making a simple spectrum analyzer app using the drawing API and the SoundMixer.computeSpectrum() method. This is basically a revised version of the example I did on my other blog last year, the poorly named “SoundMixer.computeSpectrum()” entry.

I’ve updated the code somewhat to make it a bit prettier. You can find more information on the SoundMixer class and the computeSpectrum() method in the Adobe Flash CS3 documentation “Accessing raw sound data” in the Programming ActionScript 3.0 book.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        creationComplete="init()">

    <mx:Script>
        <![CDATA[
            import mx.core.SoundAsset;

            [Embed('assets/song1.mp3')]
            private const song1:Class;

            private var mySong:SoundAsset = SoundAsset(new song1());

            private var byteArray:ByteArray = new ByteArray();

            private var timer:Timer;

            private function init():void {
                timer = new Timer(50);
                timer.addEventListener(TimerEvent.TIMER, doTimer);
            }

            private function doTimer(evt:TimerEvent):void {
                SoundMixer.computeSpectrum(byteArray, true);

                spr.graphics.clear();
                drawChannel(LEFT_CHANNEL_COLOR);
                drawChannel(RIGHT_CHANNEL_COLOR);
            }

            private function drawChannel(color:uint):void {
                var f:Number;
                var i:int;

                spr.graphics.lineStyle(1, color);
                spr.graphics.beginFill(color, 0.6);
                spr.graphics.moveTo(0, GRAPH_HEIGHT);
                for (i = 0; i < 256; i++) {
                    f = byteArray.readFloat();
                    spr.graphics.lineTo(i * 2, GRAPH_HEIGHT - ((f * GRAPH_HEIGHT)) * 0.75);
                }
                spr.graphics.lineTo(512, GRAPH_HEIGHT);
                spr.graphics.endFill();
            }

            private function playSong():void {
                mySong.play();
            }
        ]]>
    </mx:Script>

    <mx:Number id="GRAPH_WIDTH">512</mx:Number>
    <mx:Number id="GRAPH_HEIGHT">256</mx:Number>

    <mx:Number id="LEFT_CHANNEL_COLOR">0xFF0000</mx:Number>
    <mx:Number id="RIGHT_CHANNEL_COLOR">0x0000FF</mx:Number>

    <mx:ApplicationControlBar width="{GRAPH_WIDTH}">
        <mx:Label text="Left:" color="{LEFT_CHANNEL_COLOR}" fontWeight="bold" />
        <mx:Label text="Right:" color="{RIGHT_CHANNEL_COLOR}" fontWeight="bold" />
        <mx:Spacer width="100%" />
        <mx:Button label="Play" click="playSong(); timer.start()" />
    </mx:ApplicationControlBar>

    <mx:VBox id="hbox" width="{GRAPH_WIDTH}" height="{GRAPH_HEIGHT}" backgroundColor="white">
        <mx:Box id="spr" width="100%" height="100%" />
    </mx:VBox>

</mx:Application>

Here’s the modified version which uses the Flex 2 Charting components.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init()">

    <mx:Script>
        <![CDATA[
            import mx.charts.chartClasses.NumericAxis;
            import mx.core.SoundAsset;

            [Embed('assets/song1.mp3')]
            private const song1:Class;

            private var mySong:SoundAsset;
            private var byteArray:ByteArray;
            private var timer:Timer;

            private function init():void {
                byteArray = new ByteArray();

                timer = new Timer(50); /* 50 milliseconds (20x/sec) */
                timer.addEventListener(TimerEvent.TIMER, doTimer);
                timer.start();

                mySong = SoundAsset(new song1());
                // mySong.play();
            }

            private function doTimer(evt:TimerEvent):void {
                var i:int;
                var f:Number;

                SoundMixer.computeSpectrum(byteArray, true);

                leftCh.removeAll();
                for (i = 0; i < 256; i++) {
                    f = byteArray.readFloat();
                    leftCh.addItem({data:f});
                }

                rightCh.removeAll();
                for (i = 0; i < 256; i++) {
                    f = byteArray.readFloat();
                    rightCh.addItem({data:f});
                }
            }
        ]]>
    </mx:Script>

    <mx:ArrayCollection id="leftCh" />
    <mx:ArrayCollection id="rightCh" />

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="play audio" click="mySong.play();" />
    </mx:ApplicationControlBar>

    <mx:ColumnChart id="barChart" width="100%" height="100%">
        <mx:verticalAxis>
            <mx:LinearAxis minimum="0" maximum="1.4" />
        </mx:verticalAxis>

        <mx:series>
            <mx:ColumnSeries dataProvider="{leftCh}" yField="data" displayName="Left" />
            <mx:ColumnSeries dataProvider="{rightCh}" yField="data" displayName="Right" />
        </mx:series>
    </mx:ColumnChart >

</mx:Application>

{ 4 comments… read them below or add one }

1 peterd August 17, 2007 at 10:55 am

Of course, the above example lacks “visual appeal”. You could build a much nicer visualizer using something like a Flex BarChart or LineChart control. I’ll try and update the sample and give a better example using the Flex Charting Components.

Reply

2 Faisal Abid August 17, 2007 at 10:31 pm

Keep getting unsupoorted sample rate, when i put my own mp3 in ? any reason why?

Reply

3 Martin November 27, 2008 at 3:39 pm

Hello,

1) Does anyone know why all examples with ComputeSpectrum is not in sync? Music & graphic is never following each other! In some examples its just a little wrong, in others its impossible to see it should be synchronized!

2) Does anyone know if its possible to listen and compute graphic on the sound being played in a WMP object within the browser? Flash should be listening to the mixer output right?

Pls. mail me at “LoopStudio @ get2net .dk”

Reply

4 Krishna Revadigar January 4, 2009 at 9:01 pm

Hi,
When I am running this example on firefox, I am getting…. stream error. Same I could run on IE. Could you please help me to resolve this issue….
Regards,
Krishna

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: