Android Audio Recorder with Examples

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

 

The android multimedia framework provides a built in support for capturing and encoding a variety of common audio and video formats. We have a multiple ways to record audio or video but by using MediaRecorder class we can easily implement audio or video recording.

 

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.

Android Set Permissions to Record Audio

To record an audio and save it in device, our app must tell the user that it will access the device’s audio input and storage, for that we need to set multiple permissions such as RECORD_AUDIO, STORAGE and WRITE_EXTERNAL_STORAGE in our manifest file.

 

Following is the code snippet of defining the permissions in android manifest file to record audio and save it in device.

 

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

</manifest>

The RECORD_AUDIO, WRITE_EXTERNAL_STORAGE are considered as a dangerous permissions because it may pose a risk to the user’s privacy. Starting with Android 6.0 (API level 23) an app that uses a dangerous permission must ask the user for approval at run time. After the user has granted permission, the app should remember and not ask again.

Android MediaRecorder Class

In android, we can record audio or video by using MediaRecorder class in our applications. This class will provide required API’s to record audio and video.

 

To use MediaRecord class to record an audio, we need to create an instance of MediaRecorder class and set the source, output, encoding format and output file to store the recorded audio in device. After that we need to call prepare(), start(), stop(), etc. to start the audio recording in our application.

 

Following is the code snippet to use MediaRecorder to record audio in android applications.

 

MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.
MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.
THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.
AMR_NB);
recorder.setOutputFile(PATH_NAME);
recorder.prepare();
recorder.start();  
// Recording will start
...
recorder.stop();
recorder.reset();  
// You can reuse the object by going back to setAudioSource() step
recorder.release(); // Now the object cannot be reused

If you observe above code snippet, we create an instance of MediaRecorder class and added required audio source, output format, encoding format, audio file saving path, etc. to record an audio and save it in device.

 

Apart from above methods, MediaRecorder class provides a different type of methods to control audio and video recording based on requirements.

 

MethodDescription
setAudioSource() It is used to specify the source of audio to be recorded.
setVideoSource() It is used to specify the source of video to be recorded.
setOutputFormat() It is used to specify the audio / video output format.
setAudioEncoder() It is used to specify the audio encoder.
setVideoEncoder() it is used to specify the video encoder.
setOutputFile() It is used to specify the path of recorded audio / video file to be stored.
stop() It is used to stop the recording process.
start() it is used to start the recording process.
release() It is used to releases the resources which are associated with MediaRecorder object.

Now we will see how to capture an audio from device microphone, save the audio, and play it back using MediaPlayer in android application with examples.

Android Audio Recording Example

Following is the example of recording an audio from device microphone, save the audio in device memory and play it using MediaPlayer.

 

Create a new android application using android studio and give names as AudioRecorderExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
Button
       
android:id="@+id/btnRecord"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:layout_marginTop="120dp"
       
android:text="Start Recording" />
    <
Button
       
android:id="@+id/btnStop"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:text="Stop Recording" />
    <
Button
       
android:id="@+id/btnPlay"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:text="Play Recording" />
    <
Button
       
android:id="@+id/btnStopPlay"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:text="Stop Playing" />
</
LinearLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.audiorecorderexample path and write the code like as shown below

MainActivity.java

package com.tutlane.audiorecorderexample;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class MainActivity extends AppCompatActivity {
   
private Button startbtn, stopbtn, playbtn, stopplay;
   
private MediaRecorder mRecorder;
   
private MediaPlayer mPlayer;
   
private static final String LOG_TAG = "AudioRecording";
   
private static String mFileName = null;
   
public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
startbtn = (Button)findViewById(R.id.btnRecord);
       
stopbtn = (Button)findViewById(R.id.btnStop);
       
playbtn = (Button)findViewById(R.id.btnPlay);
       
stopplay = (Button)findViewById(R.id.btnStopPlay);
       
stopbtn.setEnabled(false);
       
playbtn.setEnabled(false);
       
stopplay.setEnabled(false);
       
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
       
mFileName += "/AudioRecording.3gp";

       
startbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
if(CheckPermissions()) {
                   
stopbtn.setEnabled(true);
                   
startbtn.setEnabled(false);
                   
playbtn.setEnabled(false);
                   
stopplay.setEnabled(false);
                   
mRecorder = new MediaRecorder();
                   
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                   
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                   
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                   
mRecorder.setOutputFile(mFileName);
                   
try {
                       
mRecorder.prepare();
                    }
catch (IOException e) {
                        Log.e(
LOG_TAG, "prepare() failed");
                    }
                   
mRecorder.start();
                    Toast.makeText(getApplicationContext(),
"Recording Started", Toast.LENGTH_LONG).show();
                }
               
else
               
{
                    RequestPermissions();
                }
            }
        });
       
stopbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
stopbtn.setEnabled(false);
               
startbtn.setEnabled(true);
               
playbtn.setEnabled(true);
               
stopplay.setEnabled(true);
               
mRecorder.stop();
               
mRecorder.release();
               
mRecorder = null;
                Toast.makeText(getApplicationContext(),
"Recording Stopped", Toast.LENGTH_LONG).show();
            }
        });
       
playbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
stopbtn.setEnabled(false);
               
startbtn.setEnabled(true);
               
playbtn.setEnabled(false);
               
stopplay.setEnabled(true);
               
mPlayer = new MediaPlayer();
               
try {
                   
mPlayer.setDataSource(mFileName);
                   
mPlayer.prepare();
                   
mPlayer.start();
                    Toast.makeText(getApplicationContext(),
"Recording Started Playing", Toast.LENGTH_LONG).show();
                }
catch (IOException e) {
                    Log.e(
LOG_TAG, "prepare() failed");
                }
            }
        });
       
stopplay.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
mPlayer.release();
               
mPlayer = null;
               
stopbtn.setEnabled(false);
               
startbtn.setEnabled(true);
               
playbtn.setEnabled(true);
               
stopplay.setEnabled(false);
                Toast.makeText(getApplicationContext(),
"Playing Audio Stopped", Toast.LENGTH_SHORT).show();
            }
        });
    }
   
@Override
   
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       
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() {
       
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() {
        ActivityCompat.requestPermissions(MainActivity.
this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
    }
}

If you observe above code, we are requesting permissions from user to record audio and store recorded files in device using onRequestPermissionResult method and added required functionality for audio recording and playing audio using mediaplayer based on our requirements.

 

As discussed, we need to set permissions in android manifest file (AndroidManifest.xml) to record audio and stored record audio files in device. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.tutlane.audiorecorderexample">
    <
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: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>

If you observe above code, we added required audio and storage permissions in manifest file to record and store audio files in device.

Output of Android Audio Recording Example

When we run above program in android studio we will get the result like as shown below.

 

Android Audio Recorder Example Allow Permissions to Record Audio

 

If you observe above result, when we are clicking on Start Recording button it’s asking for permission to record audio and local storage access. 

 

After giving all the required permissions, if we click on Start Recording button, the audio recording will be started by using local device microphone like as shown below.

 

Android Audio Recorder Example Result to Record Audio

 

Once the audio recording finished, click on Play Recording button to listen the audio from local device.

 

This is how we can implement an audio recording in android applications based on our requirements.