25/11/2023, 10:44 Android - Audio Capture
Menu Search tutorials, courses and ebooks...
Login
Home
Coding
HTML Ground
CSS Javascript SQL Python Java C C++
Jobs
Whiteboard
Android - Audio Capture
Tools
Android has a built in microphone through which you can capture audio and
store it , or play it in your phone. There are many ways to do that but the
most common way is through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to
use MediaRecorder class ,you will first create an instance of MediaRecorder
class. Its syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file.
Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can then
call the two basic methods prepare and start to start recording the audio.
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 1/15
25/11/2023, 10:44 Android - Audio Capture
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the
MediaRecorder class that allows you more control over audio and video
recording.
Sr.No Method & description
setAudioSource()
1
This method specifies the source of audio to be recorded
setVideoSource()
2
This method specifies the source of video to be recorded
setOutputFormat()
3
This method specifies the audio format in which audio to be stored
setAudioEncoder()
4
This method specifies the audio encoder to be used
setOutputFile()
5 This method configures the path to the file into which the recorded
audio is to be stored
stop()
6
This method stops the recording process.
release()
7 This method should be called when the recorder instance is
needed.
Example
This example provides demonstration of MediaRecorder class to capture audio
and then MediaPlayer class to play that recorded audio.
To experiment with this example , you need to run this on an actual device.
Steps Description
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 2/15
25/11/2023, 10:44 Android - Audio Capture
You will use Android studio IDE to create an Android application
1 and name it as AudioCapture under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add AudioCapture code
Modify layout XML file res/layout/activity_main.xml add any GUI
3
component if required.
4 Modify AndroidManifest.xml to add necessary permissions.
Run the application and choose a running android device and install
5
the application on it and verify the results.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.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 {
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 3/15
25/11/2023, 10:44 Android - Audio Capture
Button buttonStart, buttonStop, buttonPlayLastRecordAudio,
buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolut
CreateRandomAudioFileName(5) + "AudioRecording.3g
MediaRecorderReady();
try {
mediaRecorder.prepare();
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 4/15
25/11/2023, 10:44 Android - Audio Capture
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickLis
@Override
public void onClick(View view) throws IllegalArgumentExceptio
SecurityException, IllegalStateException {
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 5/15
25/11/2023, 10:44 Android - Audio Capture
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.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();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickLi
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.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_G
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 6/15
25/11/2023, 10:44 Android - Audio Capture
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}, RequestPermis
}
@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();
}
}
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 7/15
25/11/2023, 10:44 Android - Audio Capture
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationCon
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationCo
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
Here is the content of activity_main.xml
In the below code abc indicates the logo of tutorialspoint
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr
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"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 8/15
25/11/2023, 10:44 Android - Audio Capture
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
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="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
Here is the content of Strings.xml
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 9/15
25/11/2023, 10:44 Android - Audio Capture
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_ST
<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.example.sairamkrishna.myapplication.MainAct
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>
Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android
studio, open one of your project's activity files and click Run
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 10/15
25/11/2023, 10:44 Android - Audio Capture
icon from the toolbar. Before starting your application, Android studio will
display following images.
Now by default you will see stop and play button disable. Just press the
Record button and your application will start recording the audio. It will
display the following screen.
Now just press stop button and it will save the recorded audio to external sd
card. When you click on stop button , the following screen would appear.
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 11/15
25/11/2023, 10:44 Android - Audio Capture
Now just press the play button and and recorded audio will just start playing
on the device. The following message appears when you click on play button.
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 12/15
25/11/2023, 10:44 Android - Audio Capture
Kickstart Your Career
Get certified by completing the course
Get Started
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 13/15
25/11/2023, 10:44 Android - Audio Capture
Print Page Previous Next
Advertisements
AD
Tutorials Point is a leading Ed Tech
company striving to provide the best
learning material on technical and non-
technical subjects.
About us Terms Our Products
Company Terms of use Free Library
Our Team Privacy Policy Articles
Careers Refund Policy Coding Ground
Jobs Cookies Policy Certifications
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 14/15
25/11/2023, 10:44 Android - Audio Capture
Become a Teacher FAQ's Courses
Affiliates eBooks
Contact Us Corporate Training
Free Web Graphics
Contact Us
Tutorials Point India Private Limited, Incor9
Building, Kavuri Hills, Madhapur,
Hyderabad, Telangana - 500081, INDIA
© Copyright 2023. All Rights Reserved.
https://w w w .tutorialspoint.com/android/android_audio_capture.htm 15/15