• home
  • forum
  • my
  • kt
  • download
  • Flash Audio Spectrum Analyser

    Author: 2007-06-10 09:28:59 From:

    Content

    Introduction
    Getting started
    Track Player and Spectrum analyser
    The Track
    Using Spectrum Lab to generate spectrum data

    Introduction

    This tutorial will cover how to build a simple Audio spectrum analyser in flash with the help of other audio tools.

    Getting Started

    There are two audio toolz you'll need to download in order to follow this tutorial:

    Spectrum Laboratory

    This is a program that lets you analyse the spectrum of .wav files and generate log file that contains the spectrum data needed for our flash spectrum analyser.

    This freeware can be downloaded from here. You'll also need to download Borland's VCL40.BPL if you don't already have it on your PC. After you have downloaded it, extract VCL40.BPL to your X:\windows\system\ directory.

    If you want to know more about this program, please visit their web site at http://www.qsl.net/dl4yhf/

    dBpowerAmp Music Converter

    With this program you can convert .mp3 files to .wav or vice versa. Go to their web site to download this handy converter.



    When you have finished installing the above toolz, convert all the sound files that you will be working on to .wav files with the sampling rate of at least 16,000HZ. This will save you some time when you work with Spectrum Laboratory later.

    This spectrum analyser was designed as a tutorial material, in which data are not handled in the most efficent way, it works better with short sound loops, track time below 1 minute should work fine. But once you get the hang of how it works, find a better way to arrange the spectrum data. We will discuss possible solutions to reduce the load in later sections.

    Let's start by the main component - the track player and spectrum analyser.

    Track Player and Spectrum analyser

    You can refer to the source file "spectrumAnalyzer.fla" for this part of the tutorial. The setup for the track player looks something like this:



    The first frame of the movie is the track selection menu, the second and the third frames are the track loader, the forth frame is the control panel of the track, the fifth and sixth frames updates the spectrum bars, the movie stops at frame 10 and back to the track selection menu in frame 1.

    The laysers you have to pay attention to are the actionscript layer, the play button layer, and the display layer. The rest are just graphics.

    The play button are presented throughout the movie, but users should not be allowed to play tracks when it hasn't been loaded. Give the button a name and disable it in the frame action, don't forget to stop the movie playing:

        playButton.enabled=false;
    stop();

    Now create two button symbols one for track selection and one for playing the track, put one instance of the play button on the button layer and a track selection button for each of the tracks on the same layer.

    Create an empty movie clip symbol, drag an instance of it on to a layer you remember and name the instance "track". This is used to load the track.swf we'll create later into the movie when the user select the button. Also create a directory for each track in the directory where you put the spectrumAnalyzer.swf, name it "track#" where # is the number of your track, you can use track name if you want as long as you specify in the "thePath" variable below. Now put the following code into each button and change the "thePath" value accordingly.

        on(press){
     var thePath="track1/";
     loadMovie(thePath add "track.swf",_root.track);
     _root.track.play();
     gotoAndPlay(2);
     }
    

    We will do the code for the play button last so you will have a better understanding of how things works.

    Frame one done. Now go to frame two and create a "loading" indication and extend it to frame three. put the following frame action into frame three.

        if(_root.track._currentframe==4){
     playbutton.enabled=true;
     gotoAndStop(4);
     }else{
     gotoAndPlay(2);
     }
    

    don't use "_root.track.framesloaded>4" in the if clause. cos there is another loader in the track.swf movie.

    Now create a movie symbol for the spectrum bar as follows:



    if you are not doing a digital spectrum display like I did, you can create a shape tweened bar that goes from frame 124 to frame 200.
    After you've finished, create a movie symbol for the spectrum display, drag ten spectrum bar instances into the spectrum display symbol and name them sbar1, sbar2,...sbar10.



    Then put an instance of the spectrum display onto the root display layer and name it "spectrumDis" and go to frame 5 and put in the following frame action:

     theInterval = int( _root.track.soundChannel.position/_root.track.interval)+1;
     if (theInterval<_root.track.totalRow) {
     for (i=1; i<11; i++) {
     _root.spectrumDis["sbar" add String(i)].gotoAndStop(199+Number(_root.track["data" add String(theInterval)][i-1]));
     }
     }
    

    Frame 5 and 6 is a loop that updates the spectrum display. Let me try to explain what is going on here. In order to make a spectrum analyser we need to get the amplitudes of frequencies at different time, Spectrum Lab does that job, it records data at adjustable intervals, we now need to know at which interval the track is playing, so that we can refer to the appropriate section of the data and set the spectrum bars. Spectrum Lab records amplitude in db range from 0 to -199, the data output at a particular interval (in this tutorial I refer to as one "row") looks something like this:

    -17,-51,-55,-62,-65,-66,-64,-68,-69,-69,

    And data at the next interval are written in the next line etc... The idea is to convert these rows into arrays of ten elements, or better still a two dimensional array. Either way works, this tutorial used the earlier. So an array represents one "row" and there are hundreds of these arrays for a one minute track. Now we want to know which array represents the spectrum data of the track's current position, we first have to calculate in which interval the track is playing. Then we check if it's at the last interval, if it's not we go into a for loop which goes through each spectrum bars, get values from the array[theInterval][loopcount] and tell the spectrum bar movie clip to go to the frame 199 + data(0 to -199 remember?), but from which only 0 to about -75 are audible, and that's why you created the shape tweened bar between frame 125 and 200 in the spectrum bar symbol.

    To finish the rest of the loop go to frame 6 and put in the following frame action:

        if(theInterval<_root.track.totalRow){
     this.gotoAndPlay(4);
     }else{
     for(i=1;i<11;i++){
     _root.spectrumDis["sbar" add String(i)].gotoAndStop(124);
     }
     }

    In which _root.track.totalRow is the total number of rows calcuated in the track.swf, if the current interval is not the last interval, go back to the previous frame and update the spectrum display, else set all the spectrum bars to "0%" .

    When you've done the loop, go to frame 11 and tell it to goto the first frame.:

        gotoAndStop(1);
    

    The last thing in this section - the scripts for the play button:

        on(press){
     if(_currentframe>4&&_currentframe<11){
     _root.track.soundChannel.stop();
     theInterval=_root.track.totalRow;
     gotoAndPlay(6);
     }else{
     _root.track.gotoAndStop(5);
     play();
     }
     }
    

    One thing I need to explain here is that frame 5 in track.swf has the script that starts sound so _root.track.gotoAndStop(5) in effect plays the sound.

    The Track

    This part of the tutorial is the shortest and the easiest amongst the rest.
    In your working directory, goto the track directory that you created at the beginning of last section. Create a track.fla flash movie in the directory, you may have to remove the track.fla when you finish or you don't even need to creat the .fla file in this directory, it doesn't matter which ever way you do, just remember to put all the finished track.swf files in the appropriate track# directory. At the end of the tutorial, your swf dirctory will look something like the following:



    Below is the setup of the track.fla. The first thing to do here is to import the sound file, and go to the linkage property of the sound in the library, then select Export for ActionScript and give it a name as follows:



    The first three frame is a loader, the forth frame is treated as a ready to play state, frame five plays the track and frame six stops it. The first frame contains the following frame action:

        loadVariables("track1/data.txt",this,"POST");

    The data.txt contains two variables, "sdata" and "loadstatus", where "sdata" is the spectrum data and "loadstatus" is used to tell the flash movie the txt file has been successfully loaded. Next go to the third frame and put in the following frame action:

        if (this.loadstatus == "1") {
     this.soundChannel = new Sound(this);
     this.soundChannel.attachSound("the name you gave for the sound in linkage property");
     var dataArray = sdata.split(",");
     var Row;
     var datalength = dataArray.length;
     for (i=0; i<datalength/10; i++) {
     Row += 1;
     this["data" add String(Row)] = new Array(10);
     this["data" add String(Row)] = this.dataArray.slice(i*10, i*10+10);
     }
     delete dataArray;
     this.totalRow = Row;
     this.interval = this.soundChannel.duration/totalRow;
     this.gotoAndStop(4);
     } else {
     this.gotoAndPlay(2);
     }
    

    If the data.txt is successfully loaded, the variable sdata will be converted into an array in which one element represents one data entry, the length of that array is then copied to a local variable for later use, The array is then chopped up into smaller arrays with the array function array.slice, each array now contains ten elements. The old array is then deleted, and the total number of "rows" is recorded to be used to calculate the interval.

    The fifth frame contains the frame script that plays the sound:

    soundChannel.start();

    And the final frame contains the following frame script:

    stop();

    create one track.swf for each track and put it in the appropriate directory.

    Notice if you "test movie" when you are working with the .fla, it will give you the "error opening url" message, even if you have the data.txt in place, you must run from the spectrumAnalyzer.swf to see it work.
     

    Using Spectrum Lab to generate spectrum data

    Spectrum Lab is a specialized audio analyser, it also has many other advance features, amongst which the powerfull data logging feature. It allows you to set the interval in miliseconds at which data is written to the text file and how many frequency bands you want to log and the range.
    This tutorial will only cover up to what you need to obtain the spectrum data. The rest are left for you to explore.

    So here is what you do: open the Spectrum Lab program, you will see something like the following, first of all go to "option" -"audio setings" as follows:



    The configuration and display control panel comes up, set the sample rate to 44100Hz or 22050Hz, just make sure it's over 16000Hz.



    Then in the same panel, go to Spectrum display and type in "93" under Waterfall Scroll Intv., make sure it's in millisecond. You can try out other values for the interval, the smaller the value is the largerer the text file it generates. A 1 min track analysed with 93ms interval results in a 14K text file which took 3 seconds for a 512M Ram PII 400MHz to load the file from hard drive, just over a second in a PIII 1.2GHz, whereas 100ms interval yields a 8K txt file, and 90ms yields 27K



    In the same panel again, go to the Wave setting change the speed under the "File Analysis w/o audio reply" to Fast. Choosing this setting will speed up the analysing time, it does not affect the output of the log file.



    After setting up the Spectrum Laboratory, we have to define the format of the output data, go to "File"-"Text file export" then the "File Contents" section and enter the parameters as follows:



    When you are ready to analyse the wave file, go to the "File Export Format" panel (same as above) and go to the "Filename & Action" section. Enter the path and file name of the data file then check the Active check box to toggle the output mode. When the box is checked, the data file is locked and ready for data logging, and only Spectrum Lab can write data to the file. Spectrum lab append data to the end of the file, so make sure the data file donesn't contain spectrum data from previous runs.



    Now every thing is ready, make sure you have activated text file export then go to "File"-"Wave Files"-"Analyze input from *.WAV-file", the audio File analysis panel will pop up. Now choose 1024 pts for the FFT option and press ok, you will see the spectrum graph starts to jump. when it stops jumping, that's when it finishes analysing the wav file.



    Open the data file in notepad, you should see some thing like this:



    Delete the first line which says ",,,,,,,,,", that's the names of the columns, since we didn't declare it in "File Export Format", only the separaters were written to the file. Now type in "sdata=" infront of the first row of data, and add "&loadstatus=1" to the last line, make sure there are no carrage returns nor spaces after that and save the the file as "data.txt" in the track directory:



    So there you are, go to your swf directory run the Spectrum Analyzer.swf and see your own flash audio spectrum analyser in action.

    As you may have noticed the way in which the spectrum data are organised and that it is an external source to the movie hugely increases the processing load. One way to reduce this load is to find another spectrum analysing program that interprets data in different scale, currently Spectrum Lab only measure amplitude in db and percentages, where db ranges from 0db to -140db, the negative number means there is one "Extra" character in each data entry, and percentage ranges from 0 to some big numbers far beyond 100 which is even worse for our case. Ideally we would have used the scale 0-9 to represent the amplitude of a specific frequency band, such scale will result in a reduction of 3/4 to the current file size. Another way to achieve that is to write a mini program and use string manipulation to organise the spectrum data. And by declaring the data as a variable from within the flash movie rather than loading it from an external source, runtime performance can be noticeably boosted up.

    Coming Up Next

    Fed up with volume sliders? How about a volume roller like the one on your Hi-fi system? It can be used to build a scratchable vinyl turntable too.

    Here is an experimental piece I created with this roller.
    » Level Intermediate

    Added: : 2002-08-28
    Rating: 8.74 Votes: 31
    Hits: 3387
    » Author
    Multimedia Student eager to combine artistic skills, creativity and practical knowledge to innovate new concepts in interactive media
    » Download
    Download the files used in this tutorial.
    Download (350 kb)

    discuss this topic to forum

    relation tutorial

    No information

    Category

      3D (36)
      Math Physics (18)
      3rd Party (10)
      Navigation (70)
      Actionscripting (228)
      Optimization (17)
      Animation (166)
      Projector (11)
      Audio (54)
      Special Effects (170)
      Backend (26)
      Text Effects (92)
      Drawing (34)
      Tips and Techniques (58)
      Dynamic Content (38)
      Tricks (8)
      Games (114)
      Utilities (24)
      Getting Started (99)
      Video (59)
      Interactivity (48)
      Web Design (37)

    New

    Hot