Download, play sound, use a microphone in ActionScript 3.0

The Flash Builder 4.5 package and, in fact, the ActionScript 3.0 language provides programmers with ample opportunities to use sound in general and the microphone in particular in their flex programs and ordinary flash drives. Why is this needed? First of all, it can be useful in creating programs such as all kinds of voice chats. Also, these elements can be used in the field of information security - for example, in voice recognition systems. But in this example and in this particular article, it will be said not so much about this as about the general rules for using these elements. It should also be noted that work will be carried out with a flex application.

Microphone connection


Let's start working with a microphone, for which we will open, for example, Flash Builder 4.5 and create a Flex project on the AIR platform (a special platform that allows you to create not “flash drives” with the .swf format, but full-fledged applications - if desired, even with the installation file and digital signature ) Then we can start work. In order for the program to recognize the microphone connected to the computer, you must register the following code:
public var micro:Microphone = Microphone.getMicrophone();

After executing this line of code, the program will select the first detected sound recorder. If no devices were connected, the getMicrophone () method will return null . It may be that several sound recording devices will be connected to one computer, in which case any of them can be accessed. The following code selects the second of the connected devices:
public var micro:Microphone = Microphone.getMicrophone(2);

If the second device does not exist, null will also be returned . The index property itself, indicating the number of the requested device, is of type int, that is, an integer type.
It should be noted that if the microphone has never been used in flash-programs on your computer, the Flash Player will display a special window asking you to allow or block this microphone. When the user selects one of the options, an event of the STATUS type will be launched, which can be tracked. First you need to bind to this type of event a function that will fire when these events occur.
micro.addEventListener(StatusEvent.STATUS, onStatus);

For example, this line of code can be entered into the event handler of clicking a button, or you can write it to the onCreationComplete function - then the handler will be attached to the events immediately after the program is turned on.
import mx.controls.Alert;
protected function onStatus(e:StatusEvent):void{
if(e.code == "Microphone.Unmuted") Alert.show("Микрофон разрешен.");
else if(e.code == "Microphone.Muted") Alert.show("Микрофон был запрещен.");
}

In this short example, we create an event listener of the STATUS type, which, upon receiving a signal about the corresponding event, performs the body of the onStatus function. In this case, e.code is the value that is passed to the handler after clicking one of the buttons - enable or disable.
Now let's try to record something by speaking into a microphone. When any sounds come into the microphone, an event of the SAMPLE_DATA type is activated. To record sound from a microphone, we first create some kind of storage for it. Creating a variable of a data type such as ByteArray will help us with this.
public var bArr:ByteArray = new ByteArray;

Now, as in the previous example, add an event listener to our micro variable.
micro.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleC);

After that, we write the handler function for the SAMPLE_DATA event.
protected function onSampleC(e:SampleDataEvent):void{
var sample:Number;
bArr.clear();
while(e.data.bytesAvailable){
sample = e.data.readFloat();
bArr.writeFloat(sample);
}
}

In this example, we first clear our bArr byte array so that when you re-use the program, the second record is not written after the first to the same array. After that, we read in bytes the sound into our array until it stops.
The Microphone class also has another interesting method. It allows you to send sound from a microphone to a sound reproducing device (i.e., speakers). It looks like this:
micro.setLoopBack(true);

But along with this method, one more must be used:
mic.setUseEchoSuppression(true);

This method involves the use of special echo cancellation technology. Even with it, the sound may be slightly distorted, and without it when using micro.setLoopBack (true); you can even damage your speakers.
It is also possible to adjust the volume of the sound going through the microphone. To do this, use the gain parameter. For example, by creating an HSlider object on a form, you can write a handler function for the slider's moving event, creating a simple volume control. To do this, we write a function:
protected function onSlCh():void {
micro.gain = sl.value;
}
where sl are the id parameter values ​​of the HSlider object.

Play sound


The primary object of sound in ActionScript 3.0 is an instance of the Sound class. It is he who has such a method as play () that allows you to play sound through speakers or headphones. Our first task will be to download and play sound in mp3 format. First things first, to load an mp3 file into an object of the Sound class, you need to create the so-called URLRequest - set the path to the file. For instance:
public var urlr:URLRequest = new URLRequest("sample.mp3");

In this example, the sound is loaded from the folder of the created application project and is called sample.mp3. If you need to load an audio file from another local disk, you should create a variable of type URLRequest like this:
public var urlr:URLRequest = new URLRequest("C:/sample.mp3");

After that, you can immediately write the following code:
public var snd:Sound = new Sound(urlr);

And run the method
snd.play();
by hanging it on a handler, for example, pressing a button.

You can do it in another way, reproducing the sound when it is loaded and ready for use. To do this, again, use the event handler functions. Create an event handler that is activated when the audio file is loaded into the program:
snd.addEventListener(Event.COMPLETE, onSndReady);

In this case, the snd variable should be created not as in the previous example, but as follows:
public var urlr:URLRequest = new URLRequest("C:/sample.mp3");
public var snd:Sound = new Sound();

In the handler function of a button event, write
snd.load();

This method will load the sound file specified in urlr, and when the download is complete, it will send a COMPLETE event.
At first, we will not pass any variables to the constructor of the Sound class.
After that, create the specified onSndReady function:
function onSndReady(e:Event):void {
var lsnd:Sound = e.target as Sound;
lsnd.play();
}

As a result, as soon as the sound file specified in urlr is loaded into the program, it will be played.
It is also quite simple to write a function that will track the loading of sound during its preparation for playback. To do this, create, for example, a TextArea object on the program form. Having set the value of its property id = txt, we write according to a familiar scheme the connection of the listener for the download event:
snd.addEventListener(ProgressEvent.PROGRESS, onLoading);

After that, we will write a function that in our impromptu text log txt will output the value of the downloaded data in percent:
function onLoading(e:ProgressEvent):void {
var loaded:int = Math.round(100 *(e.bytesLoaded / e.bytesTotal));
txt.text += "Звук загружен на "+loaded+"%.";
}

As a result, the log titled txt will display the percentage of loading the audio file.

Finally, we should talk about some additional parameters of the play () method.
He has two of them - this is the startTime parameter, indicated in milliseconds, and the loops parameter, indicating how many times the downloaded sound should be repeated.
For example, snd.play (1000.3) will play the sound loaded in snd starting at 1 second, and then repeat it three times.
This concludes the article about loading and playing sound, and using the microphone in ActionScript 3.0 and their most common uses. Thank you for your attention and good luck in writing your own programs.

Also popular now: