From my experience there are two reasons that can cause the activityLevel to report -1 :
1.The user did not accept the security permissions
This is detectable with StatusEvent.STATUS and checking the mic.muted property.
mic.addEventListener(StatusEvent.STATUS, onMicrophoneStatus, false, 0, true);
private function onMicrophoneStatus(event:StatusEvent):void
{
if (event.code == "Microphone.Unmuted")
trace("Microphone access was allowed.");
else if (event.code == "Microphone.Muted")
trace("Microphone access was denied.");
}
2.The second reason seems to be more esoteric and is related to two things. Wether or not the microphone went into loopback mode ; and if the microphone has a *SampleDataEvent.SAMPLE_DATA* listener.
I can't really explain precisely the logic behind it, but I suppose that sending the microphone into loopback mode initializes some event logic. You could even do mic.setLoopBack(true); mic.setLoopBack(false);.
I wish someone could explain what is actually going in the background.
3.For you second issue related to the huge echo when the panel opens, rockabit found a nice trick to fix this. You have to set the SoundTransform property of the microphone to a soundtransform object with a volume of 0. This allows you to keep your microphone into loopback mode but prevent the huge echo and feedback as well as remove the microphone captured sound from the output.
Here's the thread for reference:
http://www.rockabit.com/2009/01/14/microphone-activitylevel-in-flash/
Finally, here's a snippet of code I use to initialize my microphone that works even when swapping mics: (snipped for clarity)
private function initializeMicrophone(micIndex:int = 0):void
{
trace("Initialize mic: "+micIndex);
var gain:int = 70;
var rate:int = 44;
var silence:int = 0;
var timeout:int = 100;
this.microphone = Microphone.getEnhancedMicrophone(micIndex);
mic.addEventListener(StatusEvent.STATUS, onMicrophoneStatus, false, 0, true);
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
mic.gain = gain;
mic.setSilenceLevel(silence, timeout);
mic.rate = rate;
var micXform:SoundTransform = new SoundTransform(0);
mic.soundTransform = micXform;
mic.codec = SoundCodec.NELLYMOSER;
mic.setUseEchoSuppression(true);
mic.setLoopBack(true);
var micOptions:MicrophoneEnhancedOptions = new MicrophoneEnhancedOptions();
micOptions.mode = MicrophoneEnhancedMode.FULL_DUPLEX;
micOptions.nonLinearProcessing = true;
micOptions.echoPath = 128;
mic.enhancedOptions = micOptions;
}
private function onSwapMicrophone():void
{
if(this.mic.index == 0)
initializeMicrophone(1);
else
initializeMicrophone(0);
}
Hope this helps!
-b
mic = Microphone.getMicrophone(newIndex);? - bmleite