How To Record Sound When Programming in the Google Android Environment

How To Record Sound When Programming in the Google Android Environment
Page content

Earlier, I had explained how to play audio files in your Android application. In this tutorial, I will show you how to record sounds in your Android applications. You may need to record sound in your Android application if you are creating a sound recorder application or an interactive game. All Android phones to date have the basic set of hardware needed to record sound such as a built in mic.

Writing code to record sound is a breeze, especially for Android based software, thanks to the MediaRecorder class and associated methods which you can directly use in your code after specifying some parameters.

This tutorial is just to illustrate how basic sound recording can be implemented. For complex implementations, you will need to dig deeper in the API.

First of all, create a new instance of the MediaRecorder class (android.media.MediaRecorder)

MediaRecorder MRX = new MediaRecorder();

Next, set the audio source or the recording device. Usually, you will want to set it to MIC

MRX.setAudioSource(MediaRecorder.AudioSource.MIC);

Now specify the output format. This is the audio format the recorded file will be stored in.

MRX.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

Also specify the AudioEncoder type

MRX.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

Finally, specify the file name where the recorded data will be stored. The Path name is the full path to the audio file.

MRX.setOutputFile(PATH_NAME);

Now, the whole setup is complete. You just need to prepare the instance by calling prepare() and call the start() and stop() functions to start / stop recording.

MRX.prepare();MRX.start();…….MRX.stop();

Once the recording is finished, you can release the resources associated with that particular instance by calling

MRX.release();

You can also reset the MediaRecorder instance to the initial state by calling

MRX.reset();

Optionally, you can also use MRX.setMaxDuration() to set the maximum duration of the recording and MRX.setMaxFileSize() to set the maximum file size used for recording.

Here is the full sample code.

MediaRecorder MRX = new MediaRecorder();

MRX.setAudioSource(MediaRecorder.AudioSource.MIC);

MRX.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

MRX.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

MRX.setOutputFile(PATH_NAME);

MRX.prepare();

MRX.start();

…….

MRX.stop();

MRX.release();