Android

Android Audio Capture

Android Audio Capture

Android devices come with a built-in microphone and you can use that to record audio files. To implement an audio recorder in your application, you need to use MediaRecorder class. This class can also be used to capture video. The following steps are required to implement this:

1. The first step is to create an android application. Let’s call our application FirstApp under our package: com.firstapp.ashulakhwan.greatlearning

2. The next step is to modify the MainActivity.java file where we are going to add our code to capture Audio. After modification, the file will have the following content:

package com.firstapp.ashulakhwan.greatlearning;

import android.media.MediaPlayer;
import android.media.MediaRecorder;

import android.os.Environment;
import android.support.v6.app.AppCompatActivity;

import android.os.Bundle;
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;

import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

   Button strtButton, stopButton, playButton, 
      pauseButton ;
   String AudioSavePathInDevice = null;
   MediaRecorder mediaRecorder ;
   Random random ;
   String RandomAudioFileName = "recorded-audio";
   public static final int RequestPermissionCode = 1;
   MediaPlayer mediaPlayer ;

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

      strtButton = (Button) findViewById(R.id.button);
      stopButton = (Button) findViewById(R.id.button2);
      playButton = (Button) findViewById(R.id.button3);
      pauseButton = (Button)findViewById(R.id.button4);

      stopButton.setEnabled(false);
      playButton.setEnabled(false);
      pauseButton.setEnabled(false);

      random = new Random();

      strtButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {

            if(checkPermission()) {

               AudioSavePathInDevice = 
                  Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + 
                     CreateRandomAudioFileName(5) + "recorded-audio.3gp";

               MediaRecorderReady();

               try {
                  mediaRecorder.prepare();
                  mediaRecorder.start();
               } catch (IllegalStateException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }

               strtButton.setEnabled(false);
               stopButton.setEnabled(true);

               Toast.makeText(MainActivity.this, "The audio recording is started", 
                  Toast.LENGTH_LONG).show();
            } else {
               requestPermission();
            }

         }
      });

      stopButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            mediaRecorder.stop();
            stopButton.setEnabled(false);
            playButton.setEnabled(true);
            strtButton.setEnabled(true);
            pauseButton.setEnabled(false);

            Toast.makeText(MainActivity.this, "The recording has stopped", 
               Toast.LENGTH_LONG).show();
         }
      });

      playButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) throws IllegalArgumentException, 
            SecurityException, IllegalStateException {
               
            stopButton.setEnabled(false);
            strtButton.setEnabled(false);
            pauseButton.setEnabled(true);

            mediaPlayer = new MediaPlayer();
            try {
               mediaPlayer.setDataSource(AudioSavePathInDevice);
               mediaPlayer.prepare();
            } catch (IOException e) {
               e.printStackTrace();
            }

            mediaPlayer.start();
            Toast.makeText(MainActivity.this, "Now playing the recorded audio", 
               Toast.LENGTH_LONG).show();
         }
      });

      pauseButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            stopButton.setEnabled(false);
            strtButton.setEnabled(true);
            pauseButton.setEnabled(false);
            playButton.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 CreateRandomAudioFileName(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, "Access granted", 
                  Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(MainActivity.this,"Access 
                  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;
   }
}

3. After that, we are going to modify the XML file to add GUI components. The contents in our activity_main.xml file will look like this:

<?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"
   android:paddingBottom = "@dimen/activity_vertical_margin"
   android:paddingLeft = "@dimen/activity_horizontal_margin"
   android:paddingRight = "@dimen/activity_horizontal_margin"
   android:paddingTop = "@dimen/activity_vertical_margin">

   <ImageView
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:id = "@+id/imageView"
      android:layout_alignParentTop = "true"
      android:layout_centerHorizontal = "true"
   />

   <Button
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Start Recording"
      android:id = "@+id/button"
      android:layout_below = "@+id/imageView"
      android:layout_alignParentLeft = "true"
      android:layout_marginTop = "40dp"
   />

   <Button
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Stop Recording"
      android:id = "@+id/button2"
      android:layout_alignTop = "@+id/button"
      android:layout_centerHorizontal = "true"
   />

   <Button
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "PLAY"
      android:id = "@+id/button3"
      android:layout_alignTop = "@+id/button2"
      android:layout_alignParentRight = "true"
      android:layout_alignParentEnd = "true"
   />

   <Button
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "PAUSE"
      android:id = "@+id/button4"
      android:layout_below = "@+id/button2"
      android:layout_centerHorizontal = "true"
      android:layout_marginTop = "14dp" 
   />
</RelativeLayout>

4. Now, we will modify the AndroidManifest.xml file for adding some permission for our application. The code snippet for the AndroidManifest.xml file is below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.firstapp.ashulakhwan.greatlearning" >
   
   <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="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.firstapp.ashulakhwan.greatlearning.MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
      </activity>
      
   </application>
</manifest>

5. Finally, you can check the results of your application by running the App on an android device or Emulator. 

After following all these steps, you will be able to record audio in your application. 
 

Top course recommendations for you

    Web Scraping with Python
    1 hrs
    Beginner
    16.4K+ Learners
    4.44  (1050)
    Visual Graphics in C
    2 hrs
    Intermediate
    17K+ Learners
    4.49  (851)
    Swift Tutorial
    2 hrs
    Beginner
    4K+ Learners
    4.49  (199)
    Systematic Inventive Thinking Innovations
    1 hrs
    Beginner
    2.5K+ Learners
    4.52  (157)
    React JS Tutorial
    2 hrs
    Beginner
    68.9K+ Learners
    4.5  (5211)
    Linux Tutorial
    2 hrs
    Beginner
    56.1K+ Learners
    4.47  (5602)
    Functions in Python
    1 hrs
    Beginner
    18K+ Learners
    4.46  (1136)
    GitHub Tutorial for Beginners
    2 hrs
    Beginner
    20.8K+ Learners
    4.45  (1480)
    Trees in Java
    2 hrs
    Beginner
    8.3K+ Learners
    4.54  (241)