Android Audio Recorder Example

This tutorial is about how to implement audio recorder in android with the help of a simple application.

MediaRecorder Class

In android, MediaRecorder class will provide a functionality to record audio or video files.

In android, to record an audio we need to use device’s microphone along with MediaRecorder class. In case, if we want to record video, we need to use device’s camera along with MediaRecorder class.

The Android multimedia framework provides built-in support for capturing and encoding common audio and video formats.

A common case of using MediaRecorder to record audio works as follows:

 MediaRecorder recorder = new MediaRecorder();
//Sets the audio source to be used for recording 
//i.e. Microphone audio source
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
       //Sets the format of the output file produced during recording.
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
       //Sets the audio encoder to be used for recording.
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
       //Sets the path of the output file to be produced.
        recorder.setOutputFile(PATH_NAME);
       //Prepares the recorder to begin capturing and encoding data.
        recorder.prepare();
       //Begins capturing and encoding data to the file 
       //specified with setOutputFile().
        recorder.start();   // Recording is now started
        ...

        recorder.stop();    //Stops recording.
        recorder.reset();   // You can reuse the object by going back to setAudioSource() step
        recorder.release(); // Now the object cannot be reused

Creating new project

1 . Create a new project by going to File  New Android Project, select Empty Activity , provide app name, select language to java and then finally click on finish.

2 . Open AndroidManifest.xml file and add the below permissions.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.c1ctech.audiorecorderapp">

    <!--Permission for recording audio and storage of audio in user's device-->
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:requestLegacyExternalStorage="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3 . Open activity_main.xml and add the below code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_start_rec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:text="Start Recording"
        android:padding="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_stop_rec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Recording"
        android:padding="10dp"
        android:layout_marginTop="20dp"
        app:layout_constraintEnd_toEndOf="@+id/btn_start_rec"
        app:layout_constraintStart_toStartOf="@+id/btn_start_rec"
        app:layout_constraintTop_toBottomOf="@+id/btn_start_rec" />

    <Button
        android:id="@+id/btn_play_rec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play Recording"
        android:padding="10dp"
        android:layout_marginTop="20dp"
        app:layout_constraintEnd_toEndOf="@+id/btn_stop_rec"
        app:layout_constraintStart_toStartOf="@+id/btn_stop_rec"
        app:layout_constraintTop_toBottomOf="@+id/btn_stop_rec" />

    <Button
        android:id="@+id/btn_stop_playing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Playing"
        android:layout_marginTop="20dp"
        android:padding="10dp"
        app:layout_constraintEnd_toEndOf="@+id/btn_play_rec"
        app:layout_constraintStart_toStartOf="@+id/btn_play_rec"
        app:layout_constraintTop_toBottomOf="@+id/btn_play_rec" />

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:textColor="@color/colorPrimaryDark"
        app:layout_constraintEnd_toEndOf="@+id/btn_stop_playing"
        app:layout_constraintStart_toStartOf="@+id/btn_stop_playing"
        app:layout_constraintTop_toBottomOf="@+id/btn_stop_playing" />

</androidx.constraintlayout.widget.ConstraintLayout>

4 . Open MainActivity.java and add the below code. It uses MediaRecorder that captures audio from a device microphone, save the audio, and play it back (with MediaPlayer).

MainActivity.java

package com.c1ctech.audiorecorderapp;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class MainActivity extends AppCompatActivity {

    private Button btnStart, btnStop, btnPlay, btnStopPlay;

    private TextView tvStatus;

    private MediaRecorder mRecorder;

    private MediaPlayer mPlayer;

    // string variable is created for storing a file name
    private static String mFileName = null;

    // constant for audio permission
    public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get views by id
        tvStatus = findViewById(R.id.tvStatus);
        btnStart = findViewById(R.id.btn_start_rec);
        btnStop = findViewById(R.id.btn_stop_rec);
        btnPlay = findViewById(R.id.btn_play_rec);
        btnStopPlay = findViewById(R.id.btn_stop_playing);

        //setting buttons background color
        btnStop.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnStopPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // start audio recording.
                startRecording();
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // stop audio recording.
                stopRecording();

            }
        });
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // play the recorded audio
                playAudio();
            }
        });
        btnStopPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // stop playing the recorded audio
                stopPlaying();
            }
        });
    }

    private void startRecording() {
        // check permission method is used to check
        // that the user has granted permission
        // to record and store the audio.
        if (CheckPermissions()) {

            //setting buttons background color
            btnStop.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnStart.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            btnPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            btnStopPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));

            //initializing filename variable
            // with the path of the recorded audio file.
            mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
            mFileName += "/AudioRecording.3gp";


            //initializing media recorder class
            mRecorder = new MediaRecorder();

            //Sets the audio source to be used for recording.
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

            // set the output format of the audio.
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

            // set the audio encoder for recorded audio.
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            //set the output file location for recorded audio
            mRecorder.setOutputFile(mFileName);
            try {

                //Prepares the recorder to begin capturing and encoding data.
                mRecorder.prepare();

            } catch (IOException e) {
                Log.e("TAG", "prepare() failed");
            }

            // start the audio recording.
            mRecorder.start();

            tvStatus.setText("Recording Started");
        } else {

            // if audio recording permissions are
            // not granted by user this method will
            // ask for runtime permission for mic and storage.
            RequestPermissions();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // this method is called when user will
        // grant the permission for audio recording.
        switch (requestCode) {
            case REQUEST_AUDIO_PERMISSION_CODE:
                if (grantResults.length > 0) {
                    boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    if (permissionToRecord && permissionToStore) {
                        Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean CheckPermissions() {
        // this method is used to check permission
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
        return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
    }

    private void RequestPermissions() {
        // this method is used to request the
        // permission for audio recording and storage.
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
    }

    //play the recorded audio
    public void playAudio() {
        btnStop.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnStart.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        btnPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnStopPlay.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

        // using media player class for playing recorded audio
        mPlayer = new MediaPlayer();
        try {

            // set the data source which will be our file name
            mPlayer.setDataSource(mFileName);

            //prepare media player
            mPlayer.prepare();

            // start media player.
            mPlayer.start();
            tvStatus.setText("Recording Started Playing");

        } catch (IOException e) {
            Log.e("TAG", "prepare() failed");
        }
    }

    public void stopRecording() {
        btnStop.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnStart.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        btnPlay.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        btnStopPlay.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

        // stop the audio recording.
        mRecorder.stop();

        // release the media recorder object.
        mRecorder.release();
        mRecorder = null;

        tvStatus.setText("Recording Stopped");
    }

    public void stopPlaying() {

        // release the media player object
        // and stop playing recorded audio.
        mPlayer.release();
        mPlayer = null;
        btnStop.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        btnStart.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        btnPlay.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        btnStopPlay.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        tvStatus.setText("Recording Play Stopped");
    }

    @Override
    public void onStop() {
        super.onStop();
        // releasing the media player and the media recorder object
        // and set it to null
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

Now when you run the app on Physical device it will look like this:

Leave a Reply