[AS3] – MICROPHONE – RECORD AND SAVE AS WAVE FILE

April 14, 2011 at 1:37 AM (Actionscript) (, , , )


Adding save feature to my previous demo Record and play, it saves the recorded sound to a wave file.

For saving the sound data to wave file I’m using wave encoder from bytearray.org

click here for a DEMO
source files:
Link 1: microphone_recandsave.zip – 22.4 KB

import flash.media.*;
import flash.events.*;
import flash.utils.ByteArray;
import flash.net.FileReference;
import org.bytearray.micrecorder.encoder.WaveEncoder;

var enco:WaveEncoder=new WaveEncoder();
var file:FileReference=new FileReference()

var ch:SoundChannel;
//ByteArray in which the recorded sound data is stored
var soundBytes:ByteArray = new ByteArray();
//ByteArray from which the recorded sound data is played
var soundO:ByteArray = new ByteArray();
//Sound object which plays the recorded sound...
var sound:Sound= new Sound();

//Gets your default microphone
var mic:Microphone = Microphone.getMicrophone();
//To check whether the application is recording the sound or not
var recMode:Boolean=false;
//To check whether the application is playing the sound or not
var playMode:Boolean=false;
//function called at start of application
function init(){
	//Sets the minimum input level that should be considered sound
	mic.setSilenceLevel(0);
	//The amount by which the microphone boosts the signal.
	mic.gain = 50;
	//The rate at which the microphone is capturing sound, in kHz.
	mic.rate = 44;
}
//function called when start Record button is clicked
function startRecord():void
{
	mic.addEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
}
//function called when stop Record button is clicked
function stopRecord():void
{
	mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
	soundBytes.position = 0;
	soundO.length=0
	soundO.writeBytes(soundBytes);
	soundO.position = 0;
	soundBytes.length=0;
}

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

function playSound():void
{
soundO.position = 0;
	sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playbackSampleHandler);
	ch=sound.play();
	ch.addEventListener(Event.SOUND_COMPLETE,onSC)
}
function stopSound():void
{
	sound.removeEventListener(SampleDataEvent.SAMPLE_DATA, playbackSampleHandler);
	ch.stop()
	ch.removeEventListener(Event.SOUND_COMPLETE,onSC)
}
function onSC(evt:Event):void
{
	trace("SOUND_COMPLETE")
	stopSound()
	soundO.position=0
	playMode=!true
		play_lab.gotoAndStop(1)
		play_mesg.gotoAndStop(1)
		rec_btn.visible=rec_lab.visible=!false
		save_btn.visible=save_lab.visible=true
}
function playbackSampleHandler(event:SampleDataEvent):void
{
	for (var i:int = 0; i < 8192; i++)
	{
		if (soundO.bytesAvailable < 4)
		{
			break
		}
		var sample:Number = soundO.readFloat();
		event.data.writeFloat(sample);
		event.data.writeFloat(sample);

	}
}
rec_lab.mouseEnabled=play_lab.mouseEnabled=save_lab.mouseEnabled=false
rec_btn.buttonMode=play_btn.buttonMode=save_btn.buttonMode=true
function showPlayUI(){
	play_btn.visible=play_lab.visible=save_btn.visible=save_lab.visible=true;
}
function hidePlayUI(){
	play_btn.visible=play_lab.visible=save_btn.visible=save_lab.visible=!true;
}
rec_btn.addEventListener(MouseEvent.CLICK,onRecord)
play_btn.addEventListener(MouseEvent.CLICK,onPlay)
save_btn.addEventListener(MouseEvent.CLICK,onSave)
function onSave(evt:MouseEvent=null):void
{
	hidePlayUI()
	soundO.position=0
	var o:ByteArray=enco.encode(soundO,1)
	file.save(o,"sample.wav")
	showPlayUI()
}
function onRecord(evt:MouseEvent=null):void
{
	if(!recMode){
		recMode=true
		rec_lab.gotoAndStop(2)
		rec_mesg.gotoAndPlay(2)
//--------------- Edit[2-11-2012] START -----------------------------//
                hidePlayUI()
//--------------- Edit[2-11-2012] END -----------------------------//
		startRecord()
	}else{
		recMode=!true
		rec_lab.gotoAndStop(1)
		rec_mesg.gotoAndStop(1)
		stopRecord()
		showPlayUI()
	}
}
function onPlay(evt:MouseEvent=null):void
{
	if(!playMode){
		playMode=true
		play_lab.gotoAndStop(2)
		play_mesg.gotoAndPlay(2)
		rec_btn.visible=rec_lab.visible=false
		save_btn.visible=save_lab.visible=!true
		playSound()
	}else{
		playMode=!true
		play_lab.gotoAndStop(1)
		play_mesg.gotoAndStop(1)
		rec_btn.visible=rec_lab.visible=!false
		save_btn.visible=save_lab.visible=true
		stopSound()
	}
}
hidePlayUI()
init()
Advertisements

27 Comments

  1. hari.S.babu said,

    Demo is not working.WHY UPLOAD USELESS FILES?

  2. pcmazwrupp@gmail.com said,

    What is some good software for a keyboard with a usb midi output?

  3. pcmazwrupp@gmail.com said,

    Dont forget the lyrics

  4. nfkkfyaoapd@gmail.com said,

    there’s no such thing in the world, you had a misunderstood, the sims karaoke doesn’t exist lol. sorry if i didn’t help

  5. priya said,

    hello sir i have to integrate it into a website and customize it such a way
    that recording are saved into a specified fixed location..so please help me to suggest changes in this code to make it work

    • sathesh said,

      hi,

      you can edit the onSave method in the demo code by including below code(and necessary functions) to enable it to send the saved recorded data to server

      var host:String = "http://yourpath/to/php";
      var request:URLRequest = new URLRequest(host);
      var loader:URLLoader = new URLLoader();
      loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
      loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
      loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
      loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
      loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
      request.contentType = 'application/octet-stream';
      request.method = URLRequestMethod.POST;
      request.data = o;
      loader.load(request);

      and use php/asp or any other at server side to save the data at server, for example the php code to save the data as ‘file.wav’ in server will be like:

      $fp = fopen( 'file.wav', 'wb' );
      fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
      fclose( $fp );
      echo "done";

  6. Geethanjali said,

    Hi there is no save option in the files provided by you. I can only record and play. Please check.

    There is a save option in the code provided by you but not in the attachment.

  7. Anonymous said,

    WHEN I DOWNLOAD THE FILES PROVIDED BY YOU I COULDN’T SEE THE SAVE OPTION.

  8. Anonymous said,

    great!!! thank you!

  9. Leandro said,

    Thanks a lot, very useful

  10. Jboero said,

    Hello,thanks for the clear and straight forward code,but i have a doubt, is that overdub function a bug or actually a feature? for overdub i mean that when you press record,and play it starts playing and keeps recording,and what is being played records back in to the recording,and so on, maybe a “is recording = true ” condition could disable the play button while recording… just a thought.

    • sathesh said,

      Hi,

      Thanks for pointing out the issue. have fixed and updated the script, demo, and source files

      • Jboero said,

        Sathesh, you keep replying after more than a year and a half,you are a true professional.

        i was wondering if there is a way to limit the ram use, the thing is that i am applying this recorder on a ios app, and i have two issues,the first is that if i keep recording for ever, i get a memory advice,and probably get my app rejected due to a bad memory use, so i was thinking ,what would be the best probably way to achieve this?:

        1)adding a timer function and restricting the user to record for only 5 seconds (just an example), and every time the user hits the record button again,clearing up the ram,i have read somewhere that when setting “position=0” you do not clear the bytes used, and they stay in memory,(correct me if i am wrong)instead,what happens is that it starts to create layers of all the recordings done in that session, maybe i am a bit paranoic,but memory is key in mobile apps,and raw data is expensive, any snippet on how would you achieve this will be very useful,i was also thinking that,when you press “stop recording” and the timer has not reached zero, the timer should be cleared,or stopped….

        2)saving files locally for further use on ios is not as easy as a desktop app or an android app (where you can save straight to the sd card), i have been searching all over the internet because of this issue, and there is almost no info at all, luckly i have found this blog:
        http://www.saumitrabhave.com/2011/11/air-ios-solving-apps-must-follow-ios.html

        where Saumitra explains how to code, to save to the local ios “allowed” directories, anyway, i guess that the recorded wav file (or mp3) would not be available to send via email or to listen in itunes,the thing is that if someone could bring all this issues together and bring a solution, lots of users will be so happy, since building apps with air for ios is so sticky, but i love it.

        by the way, your articles on using microphone with AS3 are the best i have found on the web.

        Regards!.

  11. Gansukh Dorj said,

    Hello. I need karaoke player for website. If your player can make it please contact me? My email address is: dsukhee@yahoo.com

  12. Sean said,

    Is there any way to play back at a sample rate other than 44khz? I can set the mic rate to whatever and save the file as a .wav no problem, but the default playback method here will just play the sound faster with a lower sample rate. I’ve tried using the AS3WavSound library, but alas it seems to just ignore the sample rate completely.

    • justflash said,

      Its the restriction that the encoders has…as far i saw most of the encoders available (as open source) support only 44100, 22050 or 11025 hz sample rates popforge supports 5512hz also

      • Anonymous said,

        AS3WavSound cant play 11025 also

  13. Metroid said,

    Is there a way to automatically save the sample.wav file when the save button is pressed? (just saving the file in the same directory as the .swf)

    • justflash said,

      hi, it is not possible to save automatically in flash player version(you can do this in adobe air version)..as soon as save command is called flash will open the browse dialogue box , you cannot override it..

      one workaround will be to send the wave data to a server side script and save it (for example: http://blog.joa-ebert.com/2006/05/01/save-bytearray-to-file-with-php/)

  14. [AS3] PLAY A WAVE FILE FROM LOCAL DISK « JustFlash said,

    […] one of my previous post we saw how to Record sound data with microphone and save it as wave file…but what we […]

  15. Sirisha said,

    Firstly thanks for your reply.

    So we cannot create a recorder in cs3 with out using third party tools.

    Can we in flash CS4.

    Thank you.

    • justflash said,

      hi,

      You need cs5 or above to try this API…
      However there is a workaround for this in cs4 try the below link to acheive that:
      http://swfhead.com/blog/?p=133
      [make sure you backup any file that you replace]

      • Sirisha said,

        Thanks for your quick reply .I will try it .

  16. Siri said,

    Hi ,

    Thank you for the example i have been looking the same but it is in flash CS3 can we record audio through microphone and save it and play it back ….???

    • justflash said,

      hi,

      No…Flash cs3 compiles for flash 9 only but the new microphone API which allows to fetch microphone data is available only in flash player 10.1.. so you need to use an compiler which compiles for flash player version 10.1 like(flash cs5, flex, flash develop, etc)
      [You can use flash media server to achieve the same with flash versions lower than 10.1 but that’s different concept altogether]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: