Android SDK has a lot of possibilities to take profit of the smartphones features. Amongst them, there are the possibilities to record and play audio. Today, you are going to learn how to create an Audio Recorder on Android by using the MediaRecorder API provided in Android SDK. This tutorial is also available in video on Youtube :

Part 1

Part 2

 

First, we need to define the user interface for our Audio Recorder. It consists on a simple layout with 3 buttons : one to start recording audio, the second to stop recording audio and the last to play recorded audio :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ssaurel.audiorecorder.MainActivity">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:src="@drawable/logo_ssaurel"
        android:id="@+id/logo"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Record"
        android:textSize="20sp"
        android:id="@+id/record"
        android:layout_below="@id/logo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:textSize="20sp"
        android:id="@+id/stop"
        android:layout_below="@id/record"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play"
        android:textSize="20sp"
        android:id="@+id/play"
        android:layout_below="@id/stop"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

Next step is to write the code for the Activity, connect buttons with the code to react to user events :


public class MainActivity extends AppCompatActivity {

    private Button play, stop, record;
    private MediaRecorder myAudioRecorder;
    private String outputFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        record = (Button) findViewById(R.id.record);
        stop.setEnabled(false);
        play.setEnabled(false);
        // ...
   }
}

We need to disable stop and play button when the activity is created by calling the setEnabled method with false parameter. Then, we need to define a path for the result file of the record. It will be stored in a String variable named outputFile :


String outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

Here, we choose to store the file at the root of the external storage directory. Now, it’s time to configure the MediaRecorder object that will let us to record audio :


MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

We define the audio source, the microphone here, the output format, the audio encoder and the output file where the recorded audio will be saved. The code used to start recording audio is defined into the OnClickListener implementation set for the record button :


        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAudioRecorder.prepare();
                    myAudioRecorder.start();
                } catch (IllegalStateException ise) {
                    // make something ...
                } catch (IOException ioe) {
                    // make something
                }

                record.setEnabled(false);
                stop.setEnabled(true);

                Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
            }
        });

Like you can see, before to start recording audio, you must call the prepare method of the MediaRecorder object then you can call the start method.

We make the same thing to set an OnClickListener implementation on the stop button :


        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAudioRecorder.stop();
                myAudioRecorder.release();
                myAudioRecorder = null;
                record.setEnabled(true);
                stop.setEnabled(false);
                play.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
            }
        });

Here, we stop to record audio by calling the stop method of the MediaRecorder object. Then, we need to call the release method. Last thing is to manage buttons’ state. We disable the stop button and we enable the record and play buttons. Now, we have a recorded audio file stored at the outputFile path. So, we can play the audio file :


        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = new MediaPlayer();

                try {
                    mediaPlayer.setDataSource(outputFile);
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    // make something
                }

            }
        });

To play the audio file, we are going to use the MediaPlayer API. We create a MediaPlayer instance and we set the path of the audio file to play. Before to play the audio file, we need to call the prepare method of the MediaPlayer object. Finally, we can play the file by calling the start method.

Like you can see, it’s really simple to create a basic Audio Recorder for Android. Here, you can get the complete source code :


package com.ssaurel.audiorecorder;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Button play, stop, record;
    private MediaRecorder myAudioRecorder;
    private String outputFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        record = (Button) findViewById(R.id.record);
        stop.setEnabled(false);
        play.setEnabled(false);

        outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        myAudioRecorder.setOutputFile(outputFile);

        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAudioRecorder.prepare();
                    myAudioRecorder.start();
                } catch (IllegalStateException ise) {
                    // make something ...
                } catch (IOException ioe) {
                    // make something
                }

                record.setEnabled(false);
                stop.setEnabled(true);

                Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAudioRecorder.stop();
                myAudioRecorder.release();
                myAudioRecorder = null;
                record.setEnabled(true);
                stop.setEnabled(false);
                play.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = new MediaPlayer();

                try {
                    mediaPlayer.setDataSource(outputFile);
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                    Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    // make something
                }

            }
        });

    }
}