Audio Recorder

Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class.

Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. following code snippet will tell you how to record:

public void startAudioRecord(View view) throws IOException {
    audioRecorder = new MediaRecorder();

    audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    audioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

    outputFile = ImageUtils.getOutputMediaFile(ImageUtils.FileType.MP3);
    audioRecorder.setOutputFile(outputFile.getAbsolutePath());

    audioRecorder.prepare();
    audioRecorder.start();
}

Stop recording when you think enough recording done, as:

public void stopAudioRecord(View view) {
    if(audioRecorder == null) {
        Toast.makeText(this, "Audio Recorder is null.", Toast.LENGTH_SHORT).show();
        return;
    }

    final ProgressDialog progressBar = new ProgressDialog(this);
    progressBar.setMessage("Saving audio, please wait...");
    progressBar.show();

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    audioRecorder.stop();
                    audioRecorder.release();

                    progressBar.dismiss();
                    Toast.makeText(CaptureAudioActivity.this, "File saved at: " + outputFile, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }, 1000);
}

Common Methods
Method Description
setAudioSource() This method specifies the source of audio to be recorded
setVideoSource() This method specifies the source of video to be recorded
setOutputFormat() This method specifies the audio format in which audio to be stored
setAudioEncoder() This method specifies the audio encoder to be used
setOutputFile() This method configures the path to the file into which the recorded audio is to be stored
stop() This method stops the recording process.
release() This method should be called when the recorder instance is needed.

Download: Camera2Ex.zip