Search This Blog

Support my cause by downloading

Tuesday, 26 March 2013

Audio recording example in android using MediaRecorder

Recording audio in androd is simple. This article use MediaRecoder class to record Audio, Same class is used for recording video. This below class will illustrate the complete task of recording video

Recording.java 

import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;

public class Recording extends FragmentActivity {
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        try {
            MediaRecorder recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            String str = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            recorder.setOutputFile(str + "/" + System.currentTimeMillis()
                    + ".mp3");
            try {
                recorder.prepare();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            recorder.start();
        } catch (Exception e) {
            e.getMessage();
        }
    }
}

Lets have a look how it work
recorder.setAudioSource(MediaRecorder.AudioSource.MIC) : set the source of audio. Here mic is doing the work of recording taking user voice as input

recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) : Audio format in which you want output Setting path to reuse the recorded Audio

String str = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
recorder.setOutputFile(str + "/" + System.currentTimeMillis()
                    + ".mp3");

Permission is require to record audio and to save video inside manifest

<uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Android News and source code