Thursday 21 June 2012

Voice Recording in Android

Put below code into your main Activity.

private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}

private void setButtonHandlers() {
    ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnFormat, !isRecording);
enableButton(R.id.btnStop, isRecording);
}

private void setFormatButtonCaption() {
((Button) findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
}

private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
  if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}

private void displayFormatDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = { "MPEG 4", "3GPP" };
builder.setTitle(getString(R.string.choose_format_title)).setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
}).show();
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
  @Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};

private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
        switch (v.getId()) {
          case R.id.btnStart: {
             Toast.makeText(AudioRecordingActivity.this, "Start Recording", Toast.LENGTH_SHORT).show();
                enableButtons(true);
             startRecording();
             break;
          }
          case R.id.btnStop: {
             Toast.makeText(AudioRecordingActivity.this, "Stop Recording", Toast.LENGTH_SHORT).show();
             enableButtons(false);
             stopRecording();
             break;
          }
          case R.id.btnFormat: {
             displayFormatDialog();
             break;
          }
       }
    }
};


Main.xml File:-


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dip">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"/>
 
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_info"
        android:layout_weight="1.0"
        android:textSize="20dip"/>
     
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
     
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStart"
                android:text="@string/start_recording"
                android:layout_weight="1.0"/>
             
                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStop"
                android:text="@string/stop_recording"
                android:layout_weight="1.0"/>
             
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnFormat"
                android:text="Format (mp4)"
                android:layout_weight="1.0"/>
     
    </LinearLayout>
</LinearLayout>


Add Below Permissions to manifest.xml file.

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Download Full Source Code from below link.

Voice Recording in Android

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

42 comments:

  1. hi nice tutorial. :) keep it up ...

    ReplyDelete
  2. how to view these media files in your app.?

    ReplyDelete
  3. Thank you SO much for this piece of code !
    I used several days for getting a good recording program up and running.

    ReplyDelete
  4. i applied this code but upon pressing stop button a dialog box saying "force close " will appear? how can i solve this? please help.

    ReplyDelete
    Replies
    1. If you are debugging directly into your phone disconnect the storage from your computer first...

      Delete
    2. Hi Sarah, You solved this issue ?
      I am also getting this issue but I don't know how to fix this ? Please advise..

      Delete
  5. thank you Dipak it was very useful

    ReplyDelete
  6. hi there i want to save recording to file and convert it to mp3 is it same with normal java code ?I want to use JAVE library to convert the file

    ReplyDelete
  7. hi can you help us by showing where your recordings are saved bcz my app using your code works but don't know whether it is recorded or not

    ReplyDelete
  8. I have already download this script and run my SDK but I am getting more error. from there

    ReplyDelete
  9. Hello

    Your code is really useful!
    I’m really new in java programming. I want to edit your code, to make it to do some more things :

    I want the application to be enabled by NFC, record sound (during sleep) continuously (in separated files of 1-2 minutes length and then start a new recording file), uploading each one of them (right after it’s recorded) on a server and then deleting them from the phone. Also I want to add a UTC timestamp to every file , to be able to synchronize these sounds recordings with other signals, on the same graph.

    Could you help me with any of these? Any Help would be appreciated.
    Thanks in advance!

    ReplyDelete
  10. What are all the formats Android can encode audio utilizing this code?

    ReplyDelete
  11. The link is broken. Can you update it? Thanks a lot!

    ReplyDelete
  12. I have tried this code, but only change is audio output format from "3gp" to "amr". I have test this code in tablet, code records audio fairly well but some time creates only 6 bytes file (only amr header). Can someone help me on this problem?

    ReplyDelete
  13. I downloaded the app, it is recording but the problem is that this app is interrupting my camera video recording and every app that is using audio record, does anyone know how can I add a workaround or any condition that will stop my app whenever other app uses the audio recorder?

    ReplyDelete
  14. not working!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    java.lang.RuntimeException: start failed.
    at android.media.MediaRecorder.start(Native Method)
    at com.dipak.audiorecording.AudioRecordingActivity.startRecording(AudioRecordingActivity.java:83)

    ReplyDelete
  15. nice tutorial. At present, I am using Total Recall auto call recorder app which records calls with crystal clear quality. Also i received excellent support from their end.

    ReplyDelete
  16. Hi,

    Nice tutorial, working perfectly. I need to implement voice chat feature in my application. After lang search, i know it's possible using SIP, XMPP but i'm very confused with that. In everywhere video chat implementation available, but voice chat implementation not available. I want to know work flow of voice chat implementation, how recorded voice encode and send to server and at receiver how decode and listen that audio file.

    If anyone knows the process please help me.

    ReplyDelete
  17. Thanks Tani... i used Total Recall call recorder, its great yrr...! Recording quality very clear...thanks again for suggestion

    ReplyDelete
  18. Great job!! Thank you for sharing code. it is very helpful for me. Thanks a lot! recording app

    ReplyDelete
  19. Nice post, but Total recall recording app also great...

    ReplyDelete
  20. Thanks for the code . could someone maybe help me with adding a send button so the recording could be accessible in a central location

    ReplyDelete
  21. It's really useful code but we have to care of those person who can never put this code in activity.
    So Now HALF OFF for a very limited time. Half off price is reflected in the price shown
    Total Recall android call recorder is free for 90 days, then will be limited to recording calls for 1 minute until purchased.

    ReplyDelete
  22. I have converted MIC to VOICE_CALL for recording purpose but its only taking MIC voice in call is there any solution so that i cn get both side voice

    ReplyDelete
  23. Thanks for share the calls recording ideas , nice post .

    ReplyDelete
  24. I want the recorder to stop after 1min without any stop button..how can i do that?

    ReplyDelete
    Replies
    1. Try the Handler Concept. Run() Method based Stop the Record after the 1 min Record.

      Delete
  25. hi am record 31 sec .mp4 file and using setAudioSamplingRate(8000,11025,22050,44100) but every time file size same. how to change file size.

    ReplyDelete
  26. voice recorder is a convenient and simple tool that can be used for audio recorder and voice recording. Their are many new features comes in voice recorder which help you in recording the voice.Heinrich limited provide high qualitative products of safety and technology.

    ReplyDelete
  27. Check this call recorder App it also fail to work in many devices i am trying to make it work for motorola devices but its not supporting

    ReplyDelete
  28. I really wanted to develop a brief comment so as to say thanks to you for all the nice pointers you are sharing here. My extensive internet look up has at the end of the day been honored with reputable content to write about with my contacts. I ‘d admit that most of us visitors actually are undeniably lucky to be in a remarkable network with many lovely professionals with useful hints. I feel somewhat lucky to have come across the webpage and look forward to many more excellent moments reading here. Thank you once again for everything.

    Digital Brief Sydney

    ReplyDelete
  29. I am doing an online photography course and this site has provided me with new photography insights and ideas that I will use to improve my knowledge and skills. thanks so much for sharing this article with us and in case you need article and content writing services, do not hesitate to visit our site by clicking on University Essays Writing Service.

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. We understand that students in Australia encounter different challenges in completing their Best Research Paper Writing Service. We offer College Term Paper Writing Service to students regardless of their specialty, discipline or educational level.

    ReplyDelete