Search code examples
actionscript-3audioarraysplaybackmicrophone

How to play sound from microphone byte array in AS3?


I'm trying to play sound from ByteArray captured from the microphone and I'm expecting to hear the sound from the microphone but what I get is only random, distorted sound. This is the code that I'm using now :

var playBa:ByteArray;

var player:Sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playMic);
sound.play();

var mic:Microphone = Microphone.getMicrophone();
mic.gain = 100;
mic.rate = 44;
mic.setSilenceLevel(0, 4000);
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicSample);

function playMic(e:SampleDataEvent):void
{
    if (playBa != null) e.data.writeBytes(playBa, 0, playBa.length);
}

function onMicSample(e:SampleDataEvent):void
{
    playBa = e.data;
    playBa.position = 0;
    player.play();
}

And after a few seconds of distorted sounds, this is what I got on the Output Window:

RangeError: Error #2004: One of the parameters is invalid.
at flash.media::Sound/play()
at vclass_fla::MainTimeline/onMicSample()

Please help me. I'm a totally new to AS3 and here. Any help are highly appreciated. Thanks.


Solution

  • Some Microphones are very sensitive. You need to adjust moderate settings like shown below. Also, if speakers are closer to microphone the sound get looped.

    var myMic:Microphone = Microphone.getMicrophone(); // detect microphone
    myMic.gain = 50;
    myMic.setUseEchoSuppression(true);
    myMic.setLoopBack(true);
    myMic.setSilenceLevel(50, 1000);
    

    To more about Sound Capturing try this, Capturing microphone sound data