MicRecorder LibraryWhile working on the second chapter of "What can you do with bytes ?", I came up with a tiny helper class for developers who need to record audio easily from the microphone in their applications.

Here is MicRecorder, which handles internally the ByteArray work with the Event.SAMPLE_DATA event dispatched by the Microphone object introduced in Flash Player 10.1 and the WAV packaging. The WAV encoder is bundled but any other encoder could be used in a near future ;)

Here is a little demo :

A Flash animation should have appeared here, but it seems that your browser has an older version of the Flash Player or it is not installed at all. Please, install the last release of the Flash Player now, then reload this page.

To record audio from the Microphone in your application, just use those few lines :

// volume in the final WAV file will be downsampled to 50%
var volume:Number = .5;
// we create the WAV encoder to be used by MicRecorder
var wavEncoder:WaveEncoder = new WaveEncoder( volume );
// we create the MicRecorder object which does the job
var recorder:MicRecorder = new MicRecorder( wavEncoder );
// starts recording
// stop recording

When recording starts a RecordingEvent.RECORDING event is dispatched giving infos about time. When recording it stopped an Event.COMPLETE is dispatched allowing you to retrieve the Micorder.output bytes and save the audio stream (in this case as a WAV) using a simple FileReference object :

recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
recorder.addEventListener(Event.COMPLETE, onRecordComplete);

private function onRecording(event:RecordingEvent):void
     trace ( event.time );

private function onRecordComplete(event:Event):void
     fileReference.save ( recorder.output, "recording.wav" );

You can also replay what has been recorded by passing the raw WAV file to the WavSound object from the nice as3wavsound library :

private function onRecordComplete(event:Event):void
     var player:WavSound = new WavSound(recorder.output);

The MicRecorder object relies by default on the default Microphone device available, but you can pass any Microphone instance as replacement when creating the MicRecorder object :

// a specific Microphone instance can be passed
var recorder:MicRecorder = new MicRecorder( wavEncoder, microphoneDevice );

You can download everything here.