Packageflash.media
Classpublic final class Microphone
InheritanceMicrophone Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: 

Use the Microphone class to monitor or capture audio from a microphone.

To get access to the device microphone, you can use Microphone.getMicrophone() method. However, this method returns a simple microphone, which does not have the ability to eliminate acoustic echo. In order to eliminate acoustic echo, you need to get an instance of microphone using Microphone.getEnhancedMicrophone() method. This method returns a device microphone that has the acoustic echo cancellation feature enabled for mobile. Use acoustic echo cancellation to create real-time audio/video applications that don't require headsets.

Create a real-time chat application

To create a real-time chat application, capture audio and send it to Flash Media Server. Use the NetConnection and NetStream classes to send the audio stream to Flash Media Server. Flash Media Server can broadcast the audio to other clients. To create a chat application that doesn't require headsets, use acoustic echo cancellation. Acoustic echo cancellation prevents the feedback loop that occurs when audio enters a microphone, travels out the speakers, and enters the microphone again. To use acoustic echo cancellation, call the Microphone.getEnhancedMicrophone() method to get a reference to a Microphone instance. Set Microphone.enhancedOptions to an instance of the MicrophoneEnhancedOptions class to configure settings.

Play microphone audio locally

Call the Microphone setLoopback() method to route the microphone audio directly to the local computer or device audio output. Uncontrolled audio feedback is an inherent danger and is likely to occur whenever the audio output can be picked up by the microphone input. The setUseEchoSuppression() method can reduce, but not eliminate, the risk of feedback amplification.

Capture microphone audio for local recording or processing

To capture microphone audio, listen for the sampleData events dispatched by a Microphone instance. The SampleDataEvent object dispatched for this event contains the audio data.

For information about capturing video, see the Camera class.

Runtime microphone support

The Microphone class is not supported in Flash Player running in a mobile browser.

AIR profile support: The Microphone class is supported on desktop operating systems, and iOS and Android mobile devices. It is not supported on AIR for TV devices. See AIR Profile Support for more information regarding API support across multiple profiles.

You can test for support at run time using the Microphone.isSupported property. Note that for AIR for TV devices, Microphone.isSupported is true but Microphone.getMicrophone() always returns null.

Privacy controls

Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. Your application window size must be at least 215 x 138 pixels, the minimum size required to display the dialog box, or access is denied automatically.

Content running in the AIR application sandbox does not need permission to access the microphone and no dialog is displayed. AIR content running outside the application sandbox does require permission and the Privacy dialog is displayed.

View the examples.

See also

flash.media.Camera
flash.media.MicrophoneEnhancedMode
flash.media.MicrophoneEnhancedOptions
aYo Binitie: Implementing Acoustic Echo Suppression in Flash/Flex applications
Cristophe Coenraets: Voice Notes for Android
Michael Chaize: AIR, Android, and the Microphone


Public Properties
 PropertyDefined by
  activityLevel : Number
[read-only] The amount of sound the microphone is detecting.
Microphone
  codec : String
The codec to use for compressing audio.
Microphone
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  enableVAD : Boolean
Enable Speex voice activity detection.
Microphone
  encodeQuality : int
The encoded speech quality when using the Speex codec.
Microphone
  enhancedOptions : MicrophoneEnhancedOptions
Controls enhanced microphone options.
Microphone
  framesPerPacket : int
Number of Speex speech frames transmitted in a packet (message).
Microphone
  gain : Number
The microphone gain—that is, the amount by which the microphone multiplies the signal before transmitting it.
Microphone
  index : int
[read-only] The index of the microphone, as reflected in the array returned by Microphone.names.
Microphone
  isSupported : Boolean
[static][read-only] The isSupported property is set to true if the Microphone class is supported on the current platform, otherwise it is set to false.
Microphone
  muted : Boolean
[read-only] Specifies whether the user has denied access to the microphone (true) or allowed access (false).
Microphone
  name : String
[read-only] The name of the current sound capture device, as returned by the sound capture hardware.
Microphone
  names : Array
[static][read-only] An array of strings containing the names of all available sound capture devices.
Microphone
  noiseSuppressionLevel : int
Maximum attenuation of the noise in dB (negative number) used for Speex encoder.
Microphone
  permissionManager : PermissionManager
[static][read-only] Retrieves the permission manager object for the Camera resource
Microphone
  permissionStatus : String
[static][read-only] Determine whether the application has been granted the permission to use Microphone.
Microphone
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  rate : int
The rate at which the microphone is capturing sound, in kHz.
Microphone
  silenceLevel : Number
[read-only] The amount of sound required to activate the microphone and dispatch the activity event.
Microphone
  silenceTimeout : int
[read-only] The number of milliseconds between the time the microphone stops detecting sound and the time the activity event is dispatched.
Microphone
  soundTransform : SoundTransform
Controls the sound of this microphone object when it is in loopback mode.
Microphone
  useEchoSuppression : Boolean
[read-only] Set to true if echo suppression is enabled; false otherwise.
Microphone
Public Methods
 MethodDefined by
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
 Inherited
Dispatches an event into the event flow.
EventDispatcher
  
[static] Returns a reference to an enhanced Microphone object that can perform acoustic echo cancellation.
Microphone
  
[static] Returns a reference to a Microphone object for capturing audio.
Microphone
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
Requests Microphone permission for the application.
Microphone
  
setLoopBack(state:Boolean = true):void
Routes audio captured by a microphone to the local speakers.
Microphone
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
setSilenceLevel(silenceLevel:Number, timeout:int = -1):void
Sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun.
Microphone
  
setUseEchoSuppression(useEchoSuppression:Boolean):void
Specifies whether to use the echo suppression feature of the audio codec.
Microphone
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 EventSummaryDefined by
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
   Dispatched when a microphone starts or stops recording due to detected silence.Microphone
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
   Dispatched when the application requests permission to use Microphone on the device.Microphone
   Dispatched when the microphone has sound data in the buffer.Microphone
   Dispatched when a microphone reports its status.Microphone
Property detail
activityLevelproperty
activityLevel:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The amount of sound the microphone is detecting. Values range from 0 (no sound is detected) to 100 (very loud sound is detected). The value of this property can help you determine a good value to pass to the Microphone.setSilenceLevel() method.

If the microphone muted property is true, the value of this property is always -1.

Implementation
    public function get activityLevel():Number

Throws
PermissionError — The application does not have permission to use Microphone.

See also

codecproperty 
codec:String  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

The codec to use for compressing audio. The default codec used is the Nellymoser codec. The enumeration class SoundCodec contains the various values that are valid for the codec property.

Implementation
    public function get codec():String
    public function set codec(value:String):void

Throws
PermissionError — The application does not have permission to use Microphone.

See also

enableVADproperty 
enableVAD:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

Enable Speex voice activity detection.

Implementation
    public function get enableVAD():Boolean
    public function set enableVAD(value:Boolean):void

Throws
PermissionError — The application does not have permission to use Microphone.
encodeQualityproperty 
encodeQuality:int  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

The encoded speech quality when using the Speex codec. Possible values are from 0 to 10. The default value is 6. Higher numbers represent higher quality but require more bandwidth, as shown in the following table. The bit rate values that are listed represent net bit rates and do not include packetization overhead.

Quality value Required bit rate (kilobits per second)
0 3.95
1 5.75
2 7.75
3 9.80
4 12.8
5 16.8
6 20.6
7 23.8
8 27.8
9 34.2
10 42.2

Implementation
    public function get encodeQuality():int
    public function set encodeQuality(value:int):void

Throws
PermissionError — The application does not have permission to use Microphone.

See also

enhancedOptionsproperty 
enhancedOptions:MicrophoneEnhancedOptions  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2.7

Controls enhanced microphone options. For more information, see MicrophoneEnhancedOptions class. This property is ignored for non-enhanced Microphone instances.

Implementation
    public function get enhancedOptions():MicrophoneEnhancedOptions
    public function set enhancedOptions(value:MicrophoneEnhancedOptions):void

Throws
PermissionError — The application does not have permission to use Microphone.

See also

framesPerPacketproperty 
framesPerPacket:int  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Number of Speex speech frames transmitted in a packet (message). Each frame is 20 ms long. The default value is two frames per packet.

The more Speex frames in a message, the lower the bandwidth required but the longer the delay in sending the message. Fewer Speex frames increases bandwidth required but reduces delay.

Implementation
    public function get framesPerPacket():int
    public function set framesPerPacket(value:int):void
gainproperty 
gain:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: 

The microphone gain—that is, the amount by which the microphone multiplies the signal before transmitting it. A value of 0 tells Flash Player to multiply by 0; that is, the microphone transmits no sound.

You can think of this setting like a volume knob on a stereo: 0 is no volume and 50 is normal volume. Numbers below 50 specify lower than normal volume, while numbers above 50 specify higher than normal volume. Valid values are 0 through 100, and 50 is the default value. The user can change this value in the Flash Player Microphone Settings panel.

Implementation
    public function get gain():Number
    public function set gain(value:Number):void

Throws
PermissionError — The application does not have permission to use Microphone.

See also

indexproperty 
index:int  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The index of the microphone, as reflected in the array returned by Microphone.names.

Implementation
    public function get index():int

Throws
PermissionError — The application does not have permission to use Microphone.

See also

isSupportedproperty 
isSupported:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

The isSupported property is set to true if the Microphone class is supported on the current platform, otherwise it is set to false.

Implementation
    public static function get isSupported():Boolean
mutedproperty 
muted:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: 

Specifies whether the user has denied access to the microphone (true) or allowed access (false). When this value changes, a status event is dispatched. For more information, see Microphone.getMicrophone().

Implementation
    public function get muted():Boolean

Throws
PermissionError — The application does not have permission to use Microphone.

See also

nameproperty 
name:String  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The name of the current sound capture device, as returned by the sound capture hardware.

Implementation
    public function get name():String

See also

namesproperty 
names:Array  [read-only]

Language version: ActionScript 3.0
Runtime version: 

An array of strings containing the names of all available sound capture devices. The names are returned without having to display the Flash Player Privacy Settings panel to the user. This array provides the zero-based index of each sound capture device and the number of sound capture devices on the system, through the Microphone.names.length property. For more information, see the Array class entry.

Calling Microphone.names requires an extensive examination of the hardware, and it may take several seconds to build the array. In most cases, you can just use the default microphone.

Note: To determine the name of the current microphone, use the name property.

Implementation
    public static function get names():Array

See also

noiseSuppressionLevelproperty 
noiseSuppressionLevel:int  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

Maximum attenuation of the noise in dB (negative number) used for Speex encoder. If enabled, noise suppression is applied to sound captured from Microphone before Speex compression. Set to 0 to disable noise suppression. Noise suppression is enabled by default with maximum attenuation of -30 dB. Ignored when Nellymoser codec is selected.

Implementation
    public function get noiseSuppressionLevel():int
    public function set noiseSuppressionLevel(value:int):void

Throws
PermissionError — The application does not have permission to use Microphone.
permissionManagerproperty 
permissionManager:PermissionManager  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 33.1

Retrieves the permission manager object for the Camera resource

Implementation
    public static function get permissionManager():PermissionManager
permissionStatusproperty 
permissionStatus:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 24.0

Determine whether the application has been granted the permission to use Microphone.

Implementation
    public static function get permissionStatus():String

See also

rateproperty 
rate:int  [read-write]

Language version: ActionScript 3.0
Runtime version: 

The rate at which the microphone is capturing sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz. Flash Player 10 and AIR 1.5 or later support a 16kHz rate value.

Note: If you are using the Speex codec (Microphone.codec = SoundCodec.SPEEX) for Flash Player 10 and AIR 1.5 or later, the default rate value is 16kHz. If you use the Speex codec and then change the codec value to Nellymoser (Microphone.codec = SoundCodec.NELLYMOSER), the rate continues to be set to 16kHz until you explicitly set the rate to a new value. To receive audio using Flash Player releases before Flash Player 10 and AIR releases before AIR 1.5, change both the codec and the rate values when you publish the audio.

Implementation
    public function get rate():int
    public function set rate(value:int):void

Throws
PermissionError — The application does not have permission to use Microphone.

See also

silenceLevelproperty 
silenceLevel:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The amount of sound required to activate the microphone and dispatch the activity event. The default value is 10.

Implementation
    public function get silenceLevel():Number

Throws
PermissionError — The application does not have permission to use Microphone.

See also

silenceTimeoutproperty 
silenceTimeout:int  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The number of milliseconds between the time the microphone stops detecting sound and the time the activity event is dispatched. The default value is 2000 (2 seconds).

To set this value, use the Microphone.setSilenceLevel() method.

Implementation
    public function get silenceTimeout():int

Throws
PermissionError — The application does not have permission to use Microphone.

See also

soundTransformproperty 
soundTransform:SoundTransform  [read-write]

Language version: ActionScript 3.0
Runtime version: 

Controls the sound of this microphone object when it is in loopback mode.

Implementation
    public function get soundTransform():SoundTransform
    public function set soundTransform(value:SoundTransform):void

Throws
PermissionError — The application does not have permission to use Microphone.
useEchoSuppressionproperty 
useEchoSuppression:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: 

Set to true if echo suppression is enabled; false otherwise. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Implementation
    public function get useEchoSuppression():Boolean

See also

Method detail
getEnhancedMicrophone()method
public static function getEnhancedMicrophone(index:int = -1):Microphone

Language version: ActionScript 3.0
Runtime version: AIR 2.7

Returns a reference to an enhanced Microphone object that can perform acoustic echo cancellation. Use acoustic echo cancellation to create audio/video chat applications that don't require headsets.

The index parameter for the Microphone.getEnhancedMicrophone() method and the Microphone.getMicrophone() method work the same way.

To use this method on Android, add MODIFY_AUDIO_SETTINGS permission under Android manifest additions in the application descriptor.

Important: At any given time you can have only a single instance of enhanced microphone device. All other Microphone instances stop providing audio data and receive a StatusEvent with the code property Microphone.Unavailable. When enhanced audio fails to initialize, calls to this method return null, setting a value for Microphone.enhancedOptions has no effect, and all existing Microphone instances function as before.

To configure an enhanced Microphone object, set the Microphone.enhancedOptions property. The following code uses an enhanced Microphone object and full-duplex acoustic echo cancellation in a local test:

	     var mic:Microphone = Microphone.getEnhancedMicrophone();
	     var options:MicrophoneEnhancedOptions = new MicrophoneEnhancedOptions();
	     options.mode = MicrophoneEnhancedMode.FULL_DUPLEX;
	     mic.enhancedOptions = options;
	     mic.setLoopBack(true);
	 

The setUseEchoSuppression() method is ignored when using acoustic echo cancellation.

When a SWF file tries to access the object returned by Microphone.getEnhancedMicrophone() —for example, when you call NetStream.attachAudio()— Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash Player requires to display the dialog box.)

Parameters
index:int (default = -1) — The index value of the microphone.

Returns
Microphone — A reference to a Microphone object for capturing audio. If enhanced audio fails to initialize, returns null.

See also

getMicrophone()method 
public static function getMicrophone(index:int = -1):Microphone

Language version: ActionScript 3.0
Runtime version: 

Returns a reference to a Microphone object for capturing audio. To begin capturing the audio, you must attach the Microphone object to a NetStream object (see NetStream.attachAudio()).

Multiple calls to Microphone.getMicrophone() reference the same microphone. Thus, if your code contains the lines mic1 = Microphone.getMicrophone() mic1 = air.Microphone.getMicrophone() and mic2 = Microphone.getMicrophone() mic2 = air.Microphone.getMicrophone(), both mic1 and mic2 reference the same (default) microphone.

In general, you should not pass a value for index. Simply call air.Microphone.getMicrophone() Microphone.getMicrophone() to return a reference to the default microphone. Using the Microphone Settings section in the Flash Player settings panel, the user can specify the default microphone the application should use. (The user access the Flash Player settings panel by right-clicking Flash Player content running in a web browser.) If you pass a value for index, you can reference a microphone other than the one the user chooses. You can use index in rare cases—for example, if your application is capturing audio from two microphones at the same time. Content running in Adobe AIR also uses the Flash Player setting for the default microphone.

Use the Microphone.index property to get the index value of the current Microphone object. You can then pass this value to other methods of the Microphone class.

When a SWF file tries to access the object returned by Microphone.getMicrophone() —for example, when you call NetStream.attachAudio()— Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash Player requires to display the dialog box.)

When the user responds to this dialog box, a status event is dispatched that indicates the user's response. You can also check the Microphone.muted property to determine if the user has allowed or denied access to the microphone.

If Microphone.getMicrophone() returns null, either the microphone is in use by another application, or there are no microphones installed on the system. To determine whether any microphones are installed, use Microphones.names.length. To display the Flash Player Microphone Settings panel, which lets the user choose the microphone to be referenced by Microphone.getMicrophone, use Security.showSettings().

Parameters
index:int (default = -1) — The index value of the microphone.

Returns
Microphone — A reference to a Microphone object for capturing audio.

Events
status:StatusEvent — Dispatched when a microphone reports its status. If the value of the code property is "Microphone.Muted", the user has refused to allow the SWF file access to the user's microphone. If the value of the code property is "Microphone.Unmuted", the user has allowed the SWF file access to the user's microphone.

See also


Example
The following example shows how you can request access to the user's microphone using the static Microphone.getMicrophone() method and listening for the status event. Example provided by ActionScriptExamples.com.
var mic:Microphone = Microphone.getMicrophone();
mic.setLoopBack();
mic.addEventListener(StatusEvent.STATUS, mic_status);
 
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.text = "Detecting microphone...";
addChild(tf);
 
function mic_status(evt:StatusEvent):void {
    tf.text = "Microphone is muted?: " + mic.muted;
    switch (evt.code) {
        case "Microphone.Unmuted":
            tf.appendText("\n" + "Microphone access was allowed.");
            break;
        case "Microphone.Muted":
            tf.appendText("\n" + "Microphone access was denied.");
            break;
    }
}

requestPermission()method 
public function requestPermission():void

Language version: ActionScript 3.0
Runtime version: AIR 24.0

Requests Microphone permission for the application.


Events
PermissionStatus:PermissionEvent — dispatched when the requested permission is granted/denied by the user.
setLoopBack()method 
public function setLoopBack(state:Boolean = true):void

Language version: ActionScript 3.0
Runtime version: 

Routes audio captured by a microphone to the local speakers.

Parameters
state:Boolean (default = true)

Throws
PermissionError — The application does not have permission to use Microphone.
setSilenceLevel()method 
public function setSilenceLevel(silenceLevel:Number, timeout:int = -1):void

Language version: ActionScript 3.0
Runtime version: 

Sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun.

Speex includes voice activity detection (VAD) and automatically reduces bandwidth when no voice is detected. When using the Speex codec, Adobe recommends that you set the silence level to 0.

Activity detection is the ability to detect when audio levels suggest that a person is talking. When someone is not talking, bandwidth can be saved because there is no need to send the associated audio stream. This information can also be used for visual feedback so that users know they (or others) are silent.

Silence values correspond directly to activity values. Complete silence is an activity value of 0. Constant loud noise (as loud as can be registered based on the current gain setting) is an activity value of 100. After gain is appropriately adjusted, your activity value is less than your silence value when you're not talking; when you are talking, the activity value exceeds your silence value.

This method is similar to Camera.setMotionLevel(); both methods are used to specify when the activity event is dispatched. However, these methods have a significantly different impact on publishing streams:

Parameters
silenceLevel:Number — The amount of sound required to activate the microphone and dispatch the activity event. Acceptable values range from 0 to 100.
 
timeout:int (default = -1) — The number of milliseconds that must elapse without activity before Flash Player or Adobe AIR considers sound to have stopped and dispatches the dispatch event. The default value is 2000 (2 seconds). (Note: The default value shown in the signature, -1, is an internal value that indicates to Flash Player or Adobe AIR to use 2000.)

Throws
PermissionError — The application does not have permission to use Microphone.

See also

setUseEchoSuppression()method 
public function setUseEchoSuppression(useEchoSuppression:Boolean):void

Language version: ActionScript 3.0
Runtime version: 

Specifies whether to use the echo suppression feature of the audio codec. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Echo suppression is an effort to reduce the effects of audio feedback, which is caused when sound going out the speaker is picked up by the microphone on the same system. (This is different from acoustic echo cancellation, which completely removes the feedback. The setUseEchoSuppression() method is ignored when you call the getEnhancedMicrophone() method to use acoustic echo cancellation.)

Generally, echo suppression is advisable when the sound being captured is played through speakers — instead of a headset —. If your SWF file allows users to specify the sound output device, you may want to call Microphone.setUseEchoSuppression(true) if they indicate they are using speakers and will be using the microphone as well.

Users can also adjust these settings in the Flash Player Microphone Settings panel.

Parameters
useEchoSuppression:Boolean — A Boolean value indicating whether to use echo suppression (true) or not (false).

Throws
PermissionError — The application does not have permission to use Microphone.

See also

Event detail
activityevent 
Event object type: flash.events.ActivityEvent
ActivityEvent.type property = flash.events.ActivityEvent.ACTIVITY

Language version: ActionScript 3.0
Runtime version: 

Dispatched when a microphone starts or stops recording due to detected silence.

To specify the amount of sound required to trigger this event with an activating property of true, or the amount of time that must elapse without sound to trigger this event with an activating property of false, use Microphone.setSilenceLevel().

For a Microphone object to dispatch activity events, the application must be monitoring the input, either by calling setLoopback( true ), by listening for sampleData events, or by attaching the microphone to a NetStream object.

The ActivityEvent.ACTIVITY constant defines the value of the type property of an activity event object.

This event has the following properties:

PropertyValue
activatingtrue if the device is activating or false if it is deactivating.
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object beginning or ending a session, such as a Camera or Microphone object.

See also

permissionStatusevent  
Event object type: flash.events.PermissionEvent

Language version: ActionScript 3.0
Runtime version: AIR 24.0

Dispatched when the application requests permission to use Microphone on the device. Check the value of status property to check whether the permission was granted or denied

See also

sampleDataevent  
Event object type: flash.events.SampleDataEvent
SampleDataEvent.type property = flash.events.SampleDataEvent.SAMPLE_DATA

Language version: ActionScript 3.0
Runtime version: AIR 2

Dispatched when the microphone has sound data in the buffer.

The Microphone.rate property determines the number of samples generated per second. The number of samples per event is a factor of the number of samples per second and the latency between event calls.

Defines the value of the type property of a SampleDataEvent event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
positionThe point from which audio data is provided.

Example
The following example captures 4 seconds of audio samples from the default microphone and then plays the audio back. Be sure that there is a microphone attached. The the micSampleDataHandler() is the event listener for the sampleData event of the Microphone object. The micSampleDataHandler() method gets the samples as they become available and appends their values to a ByteArray object. A Timer object is set for 4 seconds. The Timer removes the sampleData event of the Microphone object event listener, creates a Sound object, and adds a sampleData event listener for the Sound object. The sampleData event listener for the Sound object, the playbackSampleHandler() method, provides audio samples for the Sound object to play. These audio samples are retrieved from the ByteArray object that stored the Microphone samples. The samples are written to the Sound object twice since the Microphone samples are recorded in monaural sound and the Sound object requests stereo pairs of samples. The rate property of the Microphone object is set to 44, to match the 44-kHz sample rate used by Sound objects.
 
const DELAY_LENGTH:int = 4000;

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

var timer:Timer = new Timer(DELAY_LENGTH);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();

var soundBytes:ByteArray = new ByteArray();

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

function timerHandler(event:TimerEvent):void
{		
	mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
	timer.stop();
	soundBytes.position = 0;
	var sound:Sound = new Sound();
	sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playbackSampleHandler);
	sound.play();
}

function playbackSampleHandler(event:SampleDataEvent):void
{
	for (var i:int = 0; i < 8192 && soundBytes.bytesAvailable > 0; i++) 
	{
		var sample:Number = soundBytes.readFloat();
		event.data.writeFloat(sample);
		event.data.writeFloat(sample);
	}
}

The following example captures sound using echo suppression from a microphone after the user allows access to their computer's microphone. The Security.showSettings() method displays the Flash Player dialog box, which requests permission to access the user's microphone. The call to setLoopBack(true) reroutes input to the local speaker, so you can hear the sound while you run the example.

Two listeners listen for activity and status events. The activity event is dispatched at the start and end (if any) of the session and is captured by the activityHandler() method, which traces information on the event. The status event is dispatched if the attached microphone object reports any status information; it is captured and traced using the statusHandler() method.

Note: A microphone must be attached to your computer for this example to work correctly.


package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Microphone;
    import flash.system.Security;

    public class MicrophoneExample extends Sprite {
        public function MicrophoneExample() {
            var mic:Microphone = Microphone.getMicrophone();
            Security.showSettings("2");
            mic.setLoopBack(true);
                    
            if (mic != null) {
                mic.setUseEchoSuppression(true);
                mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
                mic.addEventListener(StatusEvent.STATUS, statusHandler);
            }
        }

        private function activityHandler(event:ActivityEvent):void {
            trace("activityHandler: " + event);
        }

        private function statusHandler(event:StatusEvent):void {
            trace("statusHandler: " + event);
        }
    }
}

See also

statusevent  
Event object type: flash.events.StatusEvent
StatusEvent.type property = flash.events.StatusEvent.STATUS

Language version: ActionScript 3.0
Runtime version: 

Dispatched when a microphone reports its status. If the value of the code property is "Microphone.Muted", the user has refused to allow the SWF file access to the microphone. If the value of the code property is "Microphone.Unmuted", the user has allowed the SWF file access to the microphone.

Status events are not dispatched in Adobe AIR applications; access to the microphone cannot be changed dynamically. On most platforms, AIR applications can always access the microphone. On Android, an application must specify the Android RECORD_AUDIO permission in the application descriptor. Otherwise, Android denies access to the microphone altogether.

Defines the value of the type property of a status event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
codeA description of the object's status.
currentTargetThe object that is actively processing the Event object with an event listener.
levelThe category of the message, such as "status", "warning" or "error".
targetThe object reporting its status.

See also

Examples
examples\MicrophoneExample
The following example captures sound using echo suppression from a microphone after the user allows access to their computer's microphone. The Security.showSettings() method displays the Flash Player dialog box, which requests permission to access the user's microphone. The call to setLoopBack(true) reroutes input to the local speaker, so you can hear the sound while you run the example.

Two listeners listen for activity and status events. The activity event is dispatched at the start and end (if any) of the session and is captured by the activityHandler() method, which traces information on the event. The status event is dispatched if the attached microphone object reports any status information; it is captured and traced using the statusHandler() method.

Note: A microphone must be attached to your computer for this example to work correctly.


package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Microphone;
    import flash.system.Security;

    public class MicrophoneExample extends Sprite {
        public function MicrophoneExample() {
            var mic:Microphone = Microphone.getMicrophone();
            Security.showSettings("2");
            mic.setLoopBack(true);
                    
            if (mic != null) {
                mic.setUseEchoSuppression(true);
                mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
                mic.addEventListener(StatusEvent.STATUS, statusHandler);
            }
        }

        private function activityHandler(event:ActivityEvent):void {
            trace("activityHandler: " + event);
        }

        private function statusHandler(event:StatusEvent):void {
            trace("statusHandler: " + event);
        }
    }
}