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



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-white-color has-text-color has-background" href="https://github.com/arunk7839/AudioRecorderApp" style="background-color:#520599" target="_blank" rel="noreferrer noopener"><strong>DOWNLOAD CODE</strong></a></div>
</div>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<amp-youtube layout="responsive" width="1200" height="900" data-videoid="4_rTcYor6fU" title="Android Audio Recorder Example"><a placeholder href="https://youtu.be/4_rTcYor6fU"><img src="https://i.ytimg.com/vi/4_rTcYor6fU/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Audio Recorder Example"></a></amp-youtube>
</div></figure>



<h3 class="wp-block-heading"><span style="color: #000080;"><strong><span class="s1">MediaRecorder Class</span></strong></span></h3>



<p class="p1">In android, ;<span style="color: #0000ff;"><b>MediaRecorder</b></span> ;class will provide a functionality to record audio or video files.</p>



<p class="p1">In android, to record an audio we need to use device’s <strong><span style="color: #008000;">microphone</span></strong> along with ;<b>MediaRecorder</b> ;class. In case, if we want to record video, we need to use device’s <strong><span style="color: #008000;">camera</span></strong> along with ;<b>MediaRecorder</b> ;class.</p>



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



<p><span style="color: #0000ff;"><strong>A common case of using MediaRecorder to record audio works as follows:</strong></span></p>



<pre class="wp-block-preformatted"> MediaRecorder recorder = new MediaRecorder();
<span style="color: #008000;"><strong>//Sets the audio source to be used for recording 
//i.e. Microphone audio source</strong></span>
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
<strong><span style="color: #008000;"> //Sets the format of the output file produced during recording.
</span></strong> recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
<strong><span style="color: #008000;"> //Sets the audio encoder to be used for recording.
</span></strong> recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
<strong><span style="color: #008000;"> //Sets the path of the output file to be produced.
</span></strong> recorder.setOutputFile(PATH_NAME);
<strong><span style="color: #008000;"> //Prepares the recorder to begin capturing and encoding data.
</span></strong> recorder.prepare();
 <strong><span style="color: #008000;">//Begins capturing and encoding data to the file 
 //specified with setOutputFile().</span></strong>
 recorder.start(); <span style="color: #008000;"><strong>// Recording is now started</strong></span>
 ...

 recorder.stop(); <strong><span style="color: #008000;">//Stops recording.</span></strong>
 recorder.reset(); <span style="color: #008000;"><strong>// You can reuse the object by going back to setAudioSource() step</strong></span>
 recorder.release(); <span style="color: #008000;"><strong>// Now the object cannot be reused</strong></span></pre>



<h3 class="wp-block-heading"><span style="color: #000080;"><strong>Creating new project</strong></span></h3>



<p>1 . Create a new project by going to ;<span style="color: #008000;"><b>File ;</b><span class="s1"><b>⇒</b></span></span><b><span style="color: #008000;"> ;New Android Project</span>,</b> ;select ;<span style="color: #008000;"><strong>Empty Activity</strong></span> ;, provide ;<span style="color: #008000;"><strong>app name</strong></span>, select language to ;<span style="color: #008000;"><strong>java </strong></span>and then finally click on ;<span style="color: #0000ff;"><strong>finish</strong></span>.</p>



<p>2 . Open <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> file and add the below permissions.</p>



<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span></p>



<pre class="wp-block-preformatted"><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"

 package="com.c1ctech.audiorecorderapp">;

<span style="color: #008000;"><strong> <;!--Permission for recording audio and storage of audio in user's device-->;
</strong><span style="color: #0000ff;"><strong> <;uses-permission android:name="android.permission.RECORD_AUDIO"/>;</strong></span></span><span style="color: #0000ff;">
<strong> <;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>;</strong>
<strong> <;uses-permission android:name="android.permission.STORAGE"/>;</strong></span>

 <;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>;</pre>



<p>3 . Open <span style="color: #008000;"><strong>activity_main.xml</strong></span> and add the below code.</p>



<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>



<pre class="wp-block-preformatted"><;?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>;</pre>



<p>4 . Open ;<span style="color: #008000;"><strong>MainActivity.java</strong></span> and add the below code. It uses <span style="color: #008000;"><strong>MediaRecorder</strong></span> that captures audio from a device microphone, save the audio, and play it back (with <strong><span style="color: #0000ff;"><a style="color: #0000ff;" href="https://developer.android.com/reference/android/media/MediaPlayer"><span class="s2">MediaPlayer</span></a></span></strong>).</p>



<p><span style="color: #0000ff;"><strong>MainActivity.java</strong></span></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>




<pre class="wp-block-preformatted">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;

 <span style="color: #008000;"><strong>// string variable is created for storing a file name</strong></span>
 private static String mFileName = null;

<strong><span style="color: #008000;"> // constant for audio permission
</span></strong> public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;

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

<span style="color: #008000;"><strong> // get views by id
</strong></span> 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);

<span style="color: #008000;"><strong> //setting buttons background color
</strong></span> 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) {
<span style="color: #008000;"><strong> // start audio recording.
</strong></span> startRecording();
 }
 });
 btnStop.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
<span style="color: #008000;"><strong> // stop audio recording.
</strong></span> 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) {
<span style="color: #008000;"><strong> // stop playing the recorded audio
</strong></span> stopPlaying();
 }
 });
 }

 private void startRecording() {
 <span style="color: #008000;"><strong> // check permission method is used to check
 // that the user has granted permission
 // to record and store the audio.</strong></span>
 if (CheckPermissions()) {

 <span style="color: #008000;"><strong>//setting buttons background color</strong></span>
 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));

 <span style="color: #008000;"><strong>//initializing filename variable
 // with the path of the recorded audio file.</strong></span>
 mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
 mFileName += "/AudioRecording.3gp";


 <span style="color: #008000;"><strong>//initializing media recorder class</strong></span>
 mRecorder = new MediaRecorder();

<span style="color: #008000;"><strong> //Sets the audio source to be used for recording.
</strong></span> mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

<strong><span style="color: #008000;"> // set the output format of the audio.
</span></strong> mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

<span style="color: #008000;"><strong> // set the audio encoder for recorded audio.
</strong></span> mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

<span style="color: #008000;"><strong> //set the output file location for recorded audio
</strong></span> mRecorder.setOutputFile(mFileName);
 try {

<span style="color: #008000;"><strong> //Prepares the recorder to begin capturing and encoding data.
</strong></span> mRecorder.prepare();

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

<span style="color: #008000;"><strong> // start the audio recording.
</strong></span> mRecorder.start();

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

 <span style="color: #008000;"><strong>// if audio recording permissions are
 // not granted by user this method will
 // ask for runtime permission for mic and storage.</strong></span>
 RequestPermissions();
 }
 }

 @Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
 <strong><span style="color: #008000;">// this method is called when user will
 // grant the permission for audio recording.</span></strong>
 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() {
 <span style="color: #008000;"><strong>// this method is used to check permission</strong></span>
 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() {
 <span style="color: #008000;"><strong>// this method is used to request the
 // permission for audio recording and storage.</strong></span>
 ActivityCompat.requestPermissions(MainActivity.this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
 }

 <span style="color: #008000;"><strong>//play the recorded audio</strong></span>
 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));

<span style="color: #008000;"><strong> // using media player class for playing recorded audio
</strong></span> mPlayer = new MediaPlayer();
 try {

<span style="color: #008000;"><strong> // set the data source which will be our file name
</strong></span> mPlayer.setDataSource(mFileName);

<strong><span style="color: #008000;"> //prepare media player
</span></strong> mPlayer.prepare();

<strong><span style="color: #008000;"> // start media player.
</span></strong> 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));

<span style="color: #008000;"><strong> // stop the audio recording.
</strong></span> mRecorder.stop();

<strong><span style="color: #008000;"> // release the media recorder object.
</span></strong> mRecorder.release();
 mRecorder = null;

 tvStatus.setText("Recording Stopped");
 }

 public void stopPlaying() {

 <strong><span style="color: #008000;">// release the media player object
 // and stop playing recorded audio.</span></strong>
 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();
 <span style="color: #008000;"><strong>// releasing the media player and the media recorder object
 // and set it to null</strong></span>
 if (mRecorder != null) {
 mRecorder.release();
 mRecorder = null;
 }

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

</pre>



<p><strong>Now when you run the app on Physical device it will look like this:</strong></p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://c1ctech.com/wp-content/uploads/2021/04/Screenshot_1617259698.png" alt="" class="wp-image-2500" width="394" height="700"/></figure></div>


