Hello, Developers! In this Tutorial, we will make a small app which will be able to Record, Stop and Play the Audio. Our Audio Recording app will require few permissions like permission to access External Storage and also to record the audio. The App will have 4 Buttons

  1. Record – It starts recording when clicked.
  2. Stop – It stops recording when clicked.
  3. Play – It plays the audio recorded.
  4. Stop Audio – It forcefully stops the playing audio.

Output: –

Creating New Project

Wants to learn Advance Android Application Development – Beyond basics

Step 1: Creating Project – AudioRecording

Open your Android Studio -> Create a new project -> Choose BlankActivity > Finish

After the Gradle will resolve all the dependencies, you may now continue with the app development process.

Step 2: Creating Layout

Add this code to the activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#bdbdbd"
              android:gravity="center"
              android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/mic"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff6e40"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_record"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Record"/>

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop"/>

        <Button
            android:id="@+id/btn_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Play"/>

        <Button
            android:id="@+id/btn_stopaud"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop Audio "/>
    </LinearLayout>

</LinearLayout>

You can customize the layout according to your need.The code is self-explanatory but in the case of any query feel free to leave a comment below. This file is responsible for the UI of the app

Step 3: Adding Functionality to the App

When the user clicks on the Record button, the Recording of audio will start. So first we have to check if the permissions have been given. If the permissions are given we will call the RecorderReady(). Where we will use the object of MediaRecorder class to start audio recording. We also have to consider that after one button is clicked by the user, some other features of the app shouldn’t be available. so we use setEnabled(false) for that purpose.

When the user clicks on Stop Button, media recorder object will call the stop method. stop() is used to stop recording and can be called only after start(). If stop() is called before start() or immediately after start(), the output file will not be constructed properly, so intentionally a RuntimeException is thrown if no valid audio/video data has been received after stop() is called, and the output file is cleared(deleted).  It is called before start(), IllegalStateException is thrown.

Make sure to see that we have use setEnabled(false) or setEnabled(true) to smartly deal with such situations.

checkPermission() checks for the Permission granted by the user.

Our onRequestPermissionResult() is responsible for permissions Result and prompting the user whether the Permission is accepted or not.

The Audios recorded will be saved to your Mobile Storage in the root folder. The Format is the 3gp audio format.

Add this code to the MainActivity.java file

package com.mytrendin.audiorec;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

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

public class MainActivity extends AppCompatActivity {

    public static final int RequestPermissionCode = 1;
    Button btnStart, btnStop, btnLastRec, btnStopAud;
    String AudioSavePathInDevice = null;
    MediaRecorder mediaRecorder;
    Random random;
    String RandomAudioFileName = "audio";
    MediaPlayer mediaPlayer;

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

        btnStart = (Button) findViewById(R.id.btn_record);
        btnStop = (Button) findViewById(R.id.btn_stop);
        btnLastRec = (Button) findViewById(R.id.btn_play);
        btnStopAud = (Button) findViewById(R.id.btn_stopaud);

        btnStop.setEnabled(false);
        btnLastRec.setEnabled(false);
        btnStopAud.setEnabled(false);

        random = new Random();

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkPermission()) {
                    AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + AudioFileName(5) + "AudioRecording.3gp";
                    MediaRecorderReady();
                    try {
                        mediaRecorder.prepare();
                        mediaRecorder.start();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    Toast.makeText(MainActivity.this, "Recording started", Toast.LENGTH_LONG).show();
                } else {
                    requestPermission();
                }
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaRecorder.stop();
                btnStop.setEnabled(false);
                btnLastRec.setEnabled(true);
                btnStart.setEnabled(true);
                btnStopAud.setEnabled(false);
                Toast.makeText(MainActivity.this, "Recording Completed", Toast.LENGTH_LONG).show();
            }
        });

        btnLastRec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException {
                btnStop.setEnabled(false);
                btnStart.setEnabled(false);
                btnStopAud.setEnabled(true);
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(AudioSavePathInDevice);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();
                Toast.makeText(MainActivity.this, "Recording Playing", Toast.LENGTH_LONG).show();
            }
        });

        btnStopAud.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnStop.setEnabled(false);
                btnStart.setEnabled(true);
                btnStopAud.setEnabled(false);
                btnLastRec.setEnabled(true);
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    MediaRecorderReady();
                }
            }
        });
    }

    public void MediaRecorderReady() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    public String AudioFileName(int string) {
        StringBuilder stringBuilder = new StringBuilder(string);
        int i = 0;
        while (i < string) {
            stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));
            i++;
        }
        return stringBuilder.toString();
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case RequestPermissionCode:
                if (grantResults.length > 0) {
                    boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    if (StoragePermission && RecordPermission) {
                        Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
        return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
    }

}

Related:

Play a music file in background using services

Android Audio Capture

Music Player app using MediaPlayer API in android

10+ best social media sharing WordPress plugin

Encryption using Java Android Cryptography API

Step 4: Adding Permissions

Now we need to mention Permissions required in the AndroidManifest.xml. Our Audio Recording app will require these mentioned Permissions written in <uses-permission> tag.

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

Download APK from [media-downloader media_id=”8186″ texts=”here”]

Download Project from [media-downloader media_id=”8185″ texts=”here”]

Don’t forget to share this tutorial with your Android Developer friends and also feel free to comment in case of any query.

If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts