Create a Useful Audio Recorder App in ActionScript 3

Create a Useful Audio Recorder App in ActionScript 3

Tutorial Details
  • Difficulty: Beginner
  • Platform: Flash Player 10+
  • Estimated Completion Time: 1 hour
  • Software: Flash Player CS4+

In this tutorial, we’ll learn how to develop a useful and attractive Audio Recorder application using Thibault Imbert‘s MicRecorder class. Read on to find out more!


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Brief Overview

We’ll make use of the Flash drawing tools to create an easy to use interface and the power of ActionScript 3 to make it record. The SWF will then save the sound as a WAV on your hard drive. Third party classes (but no programs) will be used to record and encode the data.


Step 2: Document Settings

Launch Flash and create a new document. Set the stage size to 400x290px and the frame rate to 24fps.


Step 3: Interface

This is the interface we’ll use for this application; a black gradient background, a central main button used to start and stop the recording, a recording bar indicator and a microphone activity indicator.

Let’s dive in and get building it.


Step 4: Background & Title

Select the Rectangle Tool (R) and create a 400×290 px rectangle and fill it with this linear gradient: #282C2D, #0C0E0E.

Again, use the Rectangle tool to create a #111111, 400×1 px line, duplicate it (Cmd + D) and move it 1px down, fill it with #353535.

Use the Text Tool (T) and write a title for your app, I used this format: Helvetica Neue Regular/Bold, 13pt, #E6E6E6.


Step 5: Rec Button

Let’s now draw the big button in the center.

Select the Oval Tool (O) and make a 146×146 px circle, fill it with this linear gradient: #EEEEEE, #9A9A9A, use the Gradient Transform Tool (F) to rotate the gradient fill.

Duplicate the shape and make it 76×76 px, center it and change the gradient fill to #C11402, #B11201.

Convert the button to MovieClip and name it recButton.

Double-click the new MovieClip to enter edit mode and create a new keyframe (Insert > Timeline > Keyframe), use the rectangle tool to create two 18×80 px bars and fill them with the last gradient.

Step 6: Mic Activity Indicator

The microphone activity indicator may take some time; it’s a timeline based indicator so you will have to modify the contents every frame.

With the Rectangle Primitive Tool (R) create a 3×15 px rounded rectangle with a corner radius of 3px and fill it with #252525. Duplicate the shape and make a 5px space between each shape, repeat this process until you reach 50 shapes.

Convert the shapes to MovieClip and name it activity, enter edit mode (double-click) and create 100 frames, 1 keyframe and 1 extra frame per shape.

Start changing the color of every shape in the keyframes until you reach the 100th frame, that is, frame 100: all shapes black, frame 98: 1 shape red, frame 96: 2 shapes red, etc.


Step 7: Recording Indicator

Select the Rectangle tool and create a 400×40 px rectangle, fill it with red #BB1301.

Duplicate the shape and resize its height to half, then change the color to white and leave only 20% of alpha.

Use the Text Tool (T) to add a recording message and create a Dynamic Field, name it counter, this will show the elapsed time since the recording started.

Convert the shape and texts to MovieClip and name it RecBar, mark the Export for ActionScript box and delete the clip from stage.


Step 8: MicRecorder Class

In order to be able to record and encode the data obtained by the microphone, we’ll need to use the MicRecorder class. Download it and move it to your project folder.


Step 9: New ActionScript Class

Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.


Step 10: Package

The package keyword allows you to organize your code into groups that can be imported by other scripts, it’s recommended to name them starting with a lowercase letter and use intercaps for subsequent words, for example: myClasses. It’s also common to name them using your company’s website: com.mycompany.classesType.myClass.

In this example, we’re using a single class, so there isn’t really a need to create a classes folder.

package
{

Step 11: Import Directive

These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.

import flash.display.Sprite;
import flash.media.Microphone;
import flash.system.Security;
import org.bytearray.micrecorder.*;
import org.bytearray.micrecorder.events.RecordingEvent;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.ActivityEvent;
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import flash.net.FileReference;

Step 12: Declare and Extend the Class

Here we declare the class using the class definition keyword followed by the name that we want for the class, remember that you have to save the file using this name.

The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.

public class Main extends Sprite
{

Step 13: Variables

These are the variables we’ll use, check out the comments in the code to find out exactly what’s going on.

private var mic:Microphone; //A microphone instance
private var waveEncoder:WaveEncoder = new WaveEncoder(); //Will encode the data captured by the microphone, part of MicRecorder
private var recorder:MicRecorder = new MicRecorder(waveEncoder); //Creates a MicRecorder instance and uses the WaveEncoder class to encode
private var recBar:RecBar = new RecBar(); //The recording indicator created before
private var tween:Tween; //A tween instance, used for animations
private var fileReference:FileReference = new FileReference(); //Used to save the encoded file to disk

Step 14: Constructor

The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.

public function Main():void
{
	//Stops the rec button and the mic indicator
	recButton.stop();
	activity.stop();

	//Starts the microphone and shows the Settings dialog to activate it
	mic = Microphone.getMicrophone();
	mic.setSilenceLevel(0);
	mic.gain = 100;
	mic.setLoopBack(true);
	mic.setUseEchoSuppression(true);
	Security.showSettings("2");

	addListeners();
}

Step 15: Initial Listeners

This function contains the necessary listeners to start the application.

private function addListeners():void
{
	//Starts recording when the rec button is activated
	recButton.addEventListener(MouseEvent.MOUSE_UP, startRecording);
	recorder.addEventListener(RecordingEvent.RECORDING, recording);
	
	recorder.addEventListener(Event.COMPLETE, recordComplete);//The recorder listens for a complete event
	activity.addEventListener(Event.ENTER_FRAME, updateMeter);//Updates the mic activity meter
}

Step 16: Start Recording

The next function is called when the user releases the Rec button, it starts by checking the availability of the microphone and then uses the MicRecorder class to capture the data generated by the microphone. The Rec button will now be used to stop the recording.

It also adds the Recording bar to stage to use as a visual alert and time counter.

private function startRecording(e:MouseEvent):void
{
	if (mic != null)
	{
		recorder.record();
		e.target.gotoAndStop(2);

		recButton.removeEventListener(MouseEvent.MOUSE_UP, startRecording);
		recButton.addEventListener(MouseEvent.MOUSE_UP, stopRecording);

		addChild(recBar);

		tween = new Tween(recBar,"y",Strong.easeOut, -  recBar.height,0,1,true);
	}
}

Step 17: Stop Recording

The Rec button will change its functionality when recording, it will now stop the recording when released.

The following code will be executed when the Rec (stop) button is activated.

private function stopRecording(e:MouseEvent):void
{
	recorder.stop(); //Stop recording

	mic.setLoopBack(false);
	e.target.gotoAndStop(1);//Change button icon

	//Change the listeners to return the buttons original function
	recButton.removeEventListener(MouseEvent.MOUSE_UP, stopRecording);
	recButton.addEventListener(MouseEvent.MOUSE_UP, startRecording);

	tween = new Tween(recBar,"y",Strong.easeOut,0, - recBar.height,1,true); //Hides the recording bar
}

Step 18: Update Activity Indicator

This function updates the Microphone activity indicator. It uses the activityLevel property to get a number from 0 to 100 and then uses it in the activity MovieClip.

private function updateMeter(e:Event):void
{
	activity.gotoAndPlay(100 - mic.activityLevel);
}

Step 19: Record

The next function sets the elapsed time in the Recording bar.

private function recording(e:RecordingEvent):void
{
	var currentTime:int = Math.floor(e.time / 1000);//Gets the elapsed time since the recording event was called

	recBar.counter.text = String(currentTime);//Sets the time to the TextField

	//Formats the text used in the time (2 digits numbers only in this example)
	if (String(currentTime).length == 1)
	{
		recBar.counter.text = "00:0" + currentTime;
	}
	else if (String(currentTime).length == 2)
	{
		recBar.counter.text = "00:" + currentTime;
	}
}

Step 20: Record Complete

When the user stops the recording, a Complete event will be dispatched and we’ll use a FileReference instance to save the recorded file to disk.

private function recordComplete(e:Event):void
{
	fileReference.save(recorder.output, "recording.wav");
}

Conclusion

The MicRecorder class is a great addition to ActionScript 3, be sure to bookmark this class to use it in your future projects.

Thanks for reading this tutorial, I hope you’ve found it useful!

  • Betraydan

    Great tut and nice class.

  • Frank Mawn

    Wow that’s great. Is there a way to get a mp3 file as the output? Stil… really powerful class !

  • http://www.deviantlogic.ca aVI

    WOOOOOWWW!!! THATS A GREAT TUT!!!!!! TIP MY HAT TO U GUYS!!!!

  • http://www.deviantlogic.ca/ Avi

    demo .fla files dont work. i get “Unexpected File Format” from Flash.
    demo .swf files do not work either, i get the following error:

    VerifyError: Error #1014: Class flash.events::SampleDataEvent could not be found.

    at global$init()
    at Main()

    Am i doing something wrong?

    • Ben Stanley

      What version of Flash are you using?

      • Avi

        Flash CS4 Pro. I finally got it to work, i just re-made the file.
        I was wondering if its possible to save the recorder output on the server?
        If it is, how can i go about doing that?

    • http://michaeljameswilliams.com/ Michael Williams

      Hey Avi, I realise this is a bit late but I’ve updated the zip with a CS4 version of the FLA :)

      Not sure what’s up with the SWF, though, it works for me. Anyone else getting that error?

      • http://www.deviantlogic.ca Avi

        Hey Michael, Thanks for the update! would you happen to know how or if i can save the recorder output on the server (hopefully without FMS!)
        Thanks again!

  • http://timbly.com Tim

    Should be possible to save to the server. Create a form on the server that can accept a file upload. Create a URLRequest in AS3 to go to that form and call the .upload(request) method on the file reference. Trying it now.

    • http://www.deviantlogic.ca Avi

      Hi Tim. thanks for the insight!
      Thing is.. will the “Select File” flash.net.FileReference dialog still show? but if your example does work, would u please share it with me!!
      Thanks

  • Pingback: Create a Useful Audio Recorder App in ActionScript 3 | Activetuts+ | Flash Designers

  • Pingback: Create a Useful Audio Recorder App in ActionScript 3 | Activetuts+ « action script

  • kedicik

    Hello! I cant record/ it is not work
    Why? help me please

  • http://www.e11world.com e11world

    Extremely useful! A great class.

  • kedicik

    this class doesnot work
    why?

  • marco

    also getting the same error:
    VerifyError: Error #1014: Class flash.events::SampleDataEvent could not be found.
    at global$init()
    at Main()

    as well in AS3 SampleDataEvent comes up as an error:
    1046: Type was not found or was not a compile-time constant: SampleDataEvent.

  • Jonathan Davies

    The saved file is blank the recording counter does not change so can only assume its not actualy recording has any one else got this to work yet?

    • Jonathan Davies

      scrub above post just relised the pc i was testing on was using older version of flash player sorted now.
      But is there a way to be able to set the name to save the file via the flash application and save file to server instead of local file?

  • Yulia Kovaleva

    Wow, this is something that i have been looking for for ages! Is there a way to somehow play it back in the swf?

  • Mike

    Anybody had any luck with the server upload?
    A little hint on how to do that would be greatly appreciated. And again. Thanks for a great tutorial.

  • A student

    Hello,

    for school I have to make a flashprogram wich records sound and then save it. I found this tutorial which should do that all. At first I wanted to know if the programm you made worked? And therefor I tested you’re finished program. But unfortuanally it doesn’t work the way it should.

    When I push the record button, I can hear my own voice through the computer and I can see the time line (undernead) moving, but the recording indicator (above) doesn’t indicate that the time is moving.
    When I saved the sound, and tried to play the recorded sound, I heard nothing.That’s because there’s nothing recorded, the file notes that there hasn’t recorded any time.
    And when I tried it the second time, the time line also doesn’t work.

    Could any one please help me with this problem??

  • http://michaeljameswilliams.com/ Michael Williams

    If the SWF isn’t working, you probably need to update your Flash Player to version 10 or above. If the code/FLA isn’t working, you probably need to update your copy of Flash Professional to CS4 or above.

  • James

    WOW ~It’s very very useful for me!!!!!!!
    But I have a problem that I don’t know how to modify your source codes so that
    I can play and listen the record before I save it.

    I can’t figure out how to deal with the “recorder.output”…….

  • mado

    WOW GREAT TUT- and thanks for sharing it , But there is any way to get a “mp3″ file as the output ???

  • zangwoosung

    Oh, great. I am goint to test it right away.

    Thanks. man.

  • http://busancampus.com zangwoosung

    I tried it with no success.

    I wonder what I did wrong. mine is flash cd4 pro.

    it looks okay, but it did not record my voice. and the count did not change. when I record button, it made strage sound, getting louder and louder. I had to close it down. any hint will be appreciated. happy new year.

  • A Student

    Hello,

    we have CS4 on school but is still doesn’t work. I have still got the same problem, just as zangwoosung.

  • http://gsidzn.com George

    Great work!

    Any advice on how to store the recorded audio temporarily so user can compare their recording to an audio in the library?

    Any pointers / advice would be greatly appreciated.

    Cheers!

  • stephen

    This is super cool. I have used it on my mac at home but on PCs I have had mixed results. Firstly there is no file extension…not a big deal. I have though found that some of the files are blank entirely or just wont open at all. Any ideas?

    Stephen

  • justin

    this was just the tutorial I needed. However I too git all the error messages and example didnt record.
    I also wanted to learn how to save the audio to the server instead of locally. if anyone figures it out, let us know here, yeah?

  • Danny

    Great… I was getting the same errors as everyone else with the file not recording any sound etc, but that was because i was only testing it within Flash, however once I published the file and used my browser it worked perfectly.

    I would also like a few others, like to save the file to the server and also listen to it before saving if possible. Does anyone have any idea how to do this? Also when the gain is set to 100, i get alot of weird noise coming through that gets gradually louder.

    Thanks

    • Danny

      Also i would like to know how to allow multiple usage, as at present once you have recorded a sound, the recorded stops, although it is possible to record, there is no meter etc. Thanks again

  • http://think360studio.com/ Think360 Studio – Web Design Company

    wow great :)

  • tunq

    Thank u very much for your share.
    I want to update it, because after i recoder and save to file.wav. I listen the music file, it very noise . T_T.
    Can you suggest me some solution.
    Thanks.

  • Reza Neiriz

    Hi,
    The source files do not record anything. The timer does not work either. However, the sample on this page works fine. So, I don’t think the flash player version is the issue. What’s the problem?

    Thanks

  • sergo

    dont recording
    always time recording….00:00
    and save file 44 byte
    (adobe player 10)

    • http://waqaralamgir.co.cc/ Waqar Alamgir

      The same issues I am facing, any luck?

  • batur

    how to play back recorder.output?

  • Subbu

    HI,
    This is a great tutorial. Is there a way that we can save files in mp3 format?

    thanks

  • Mauro Hernandez

    Great tool Carlos! can I use your code in one of my Flash project? are there any copyrights issues?

  • http://www.discourse.ir Payman Karimi

    My hellos to Mr Neiriz!

  • John Volks

    To the people having problems running this tutorial, you need Flash Player 10.1 and up. If you have CS4, the flash player debugger that comes with it is not 10.1 (I think it is 10.0). To run this in CS4, you need to download the latest Flex sdk or one that contains the flash player debugger version 10.1 and up. You take the player from the sdk and replace the one located where Flash CS4 is installed.

  • Supriya Tenany

    Hi,

    Works with CS5, though there is a lot of noise during recording and the actual sound to be recorded is ebbed.

    Please suggest what can be done.

    Also, is it possible to multiplex it with a background score and display and match lyrics?

  • Pritam

    Hi, I am embading recorder swf into my local swf to add the recoding feature as it is…but I am getting same
    “VerifyError: Error #1014: Class flash.events::SampleDataEvent could not be found.

    at Main()”

    error. Though I am using latest flash version Adobe Flash Professional CS5 and while compiling the my local flash (any dummy flash game) it is giving the above error.

    Also I have tried to add AS code to workout instead of adding ready made compiled version of the recorder but same issue is giving while declaring SampleDataEvent Event.

    Please help me out to work this smoothly…
    Thanks in advanced.

  • http://www.sajithmr.me Sajith

    The Source code helped me to start learning Flash. Thanks a much for this sharing.

  • pushpa

    hi, its downloading a wav file of size 1kb. please help

  • pushpa

    i have flash player 10.3 installed in my machine.

  • raph

    Thanks for the great tut. I have worked out how to to convert the wav to a mp3 using ‘Shinemp3encoder’. However, I still get nasty a nasty feedback loop when I try and record (especially if I have the volume up high). Does anyone know of any way I can prevent this? I’d love to have cleaner recordings.

  • Rami

    Great, I need to save the file automatically save or pass to server.. how it possible using this script .. ?

    • José Miguel Jimenez

      Did you ever find out how to achieve this? Please let me know how if you did. Thanks!

  • http://next-street Naveen

    Hi,

    did any record and save on server rather dispacthing??

    • http://michaeljameswilliams.com/ Michael James Williams

      No, this doesn’t save the output to a server.

  • Biz

    I get very nasty feedback when it’s loaded in an HTML page and running through a browser. I hurry up, hit record and stop record and the feedback then goes away and is fine after that. How can I prevent this nasty feedback at the start? I can’t use this until I figure this feedback issue out.
    I appreciate any help!

    • http://michaeljameswilliams.com/ Michael James Williams

      That’s weird; I’ve not heard of that error before. Which browser and Flash version are you using?

  • Aimee

    Can someone explain to me about Flash Media Server? This tutorial seems like a fairly simple solution but all my other research on the subject made it sound quite complex involving the installation of FMS?

    • BobTheCoolGuy

      Flash didn’t use to have the capabilities to record sounds from a microphone, so you had to use Flash Media Server. However, there’s no need for that anymore, so you don’t have to worry about installing it. Actionscript’s tools for working with sound have drastically improved in the past few years.

  • http://pouthapioume.gr Konstantinos

    This is really great!

    It’s urgent to find a way to upload the file to server. I have searched ALL Internet for ages but no result!

    Cons.
    a. Can’t save other filename but recording.wav

    Thank you for this great piece of art!

    Any solution for upload?

  • http://confessions.paulbucci.ca Paul

    If you’re having a problem with feedback, comment out the line:
    mic.setLoopBack(true);

    To upload via php:

    var request:URLRequest = new URLRequest ( ‘your-php-uploader.php’ );
    var loader: URLLoader = new URLLoader();
    request.contentType = ‘application/octet-stream’;
    request.method = URLRequestMethod.POST;
    request.data = recorder.output;
    loader.load( request );

    And the php code:

    $fp = fopen( ‘your-recording-name’ . mktime() . ‘.wav’, ‘wb’ ); //mktime() is a timestamp
    fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
    fclose( $fp );

    • Dvex

      The first part of your code… This will replace the code of the method recordComplete().. Or i’m wrong?

  • student

    My code in the main.as class is working fine no errors, however when i play the swf the rec button is constantly flicking between the pause and play :( which doesnt allow me to record.

    Interface – tick
    Main.as – tick
    micrecorder downloaded into file – tick

    am i missing anything else?

  • scott

    how do I play back the recording after i have completed the recording

  • Alok Jain

    Is this possible to store .wav file on server, instead of providing it for download?

  • Rainer

    Could you provide a sample Javascript file where this recorder is embedded?