Monday, February 8, 2010

Fetching data from the microhpone and recording sound.

Hello All,

This tutorial will b short and maybe not fairly complete , but i will be talkin about the major functions and datastructures you would need to fetch data from the microhpne and store it on your system.

The following is ta brief code snippet:

protected function startRecording():void
{
microphone = Microphone.getMicrophone();
microphone.rate = 44;
microphone.gain = 100;
soundClip = new ByteArray();
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
}

The line microphone = Microphone.getMicrophone(); gets an object by the name microphone which allows you to handle and control the data from the microphone attached on your system.This will return a null if no microphone is detected on your system.The rate , is the rate of data fetch and the gain is the amount of amplification to the sound input.The soundClip object is simply put an array.

The method microphone.addEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
is the major function for fetching data from the microphone, this says that whenever the sampling is done by the soundcard and the data is being fed to the OS, an event is triggered, and the function microphone_sampleDataHandler() is called.

protected function microphone_sampleDataHandler(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
soundClip.writeFloat(sample);
}
}

In the function above , the data being fetched from sample , i.e event.data.readFloat() is being written into the array.
protected function stopRecording():void
{
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
saveNote();
subject.text = "";
}

In the function saveNote() you can write the soundClip array into a file, or a database, or any kind of saving you need to do.


Lets hope this tute was helpfule.

Keep Flexing!

1 comment:

Anonymous said...

Thanks for the post - it solves a problem that I was having. I hadn't set the 'gain' property on my Microphone instance, and all of my sample values were coming in as zero.

Post a Comment