Creating Audio Recorder in Android Android Java by Rajesh Kumar Sahanee - June 9, 2016February 13, 20200 Post Views: 5,222 Hello Friends, Today I am going to share audio recording code in android. This code will work on latest version of android (Marshmallow) also. In this code we are going to use MediaRecorder class to record audio and MediaPlayer class to play recorded audio. activity_main.xml activity_main.xml <?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" tools:context="com.zatackcoder.audiorecorder.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Notification goes here.." android:textAlignment="center" android:id="@+id/notificationTV" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Record" android:id="@+id/startB" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="170dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/stopB" android:layout_below="@+id/startB" android:layout_alignLeft="@+id/startB" android:layout_alignStart="@+id/startB" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play" android:id="@+id/playB" android:layout_below="@+id/stopB" android:layout_centerHorizontal="true" /> </RelativeLayout> 12345678910111213141516171819202122232425262728293031323334353637383940414243 <?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" tools:context="com.zatackcoder.audiorecorder.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Notification goes here.." android:textAlignment="center" android:id="@+id/notificationTV" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Record" android:id="@+id/startB" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="170dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/stopB" android:layout_below="@+id/startB" android:layout_alignLeft="@+id/startB" android:layout_alignStart="@+id/startB" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play" android:id="@+id/playB" android:layout_below="@+id/stopB" android:layout_centerHorizontal="true" /></RelativeLayout> MainActivity.java MainActivity.java package com.zatackcoder.audiorecorder; import android.Manifest; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { TextView notificationTV; Button startB; Button stopB; Button playB; MediaRecorder recorder; File audiofile; Boolean recording = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); notificationTV = (TextView)findViewById(R.id.notificationTV); startB = (Button)findViewById(R.id.startB); stopB = (Button)findViewById(R.id.stopB); playB = (Button)findViewById(R.id.playB); startB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(recording){ Toast.makeText(getApplicationContext(), "Already recording stop first", Toast.LENGTH_LONG).show(); return; } recorder = new MediaRecorder(); try { audiofile = File.createTempFile("sound", ".amr", Environment.getExternalStorageDirectory()); } catch (IOException e) { e.printStackTrace(); } recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); Toast.makeText(getApplicationContext(), audiofile.getAbsolutePath(), Toast.LENGTH_LONG).show(); try { recorder.prepare(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); return; } recorder.start(); // Recording is now started recording = true; notificationTV.setText("Recording..."); Toast.makeText(getApplicationContext(), "Recording started!", Toast.LENGTH_LONG).show(); } }); stopB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!recording){ Toast.makeText(getApplicationContext(), "Recording not started yet!", Toast.LENGTH_LONG).show(); return; } recorder.stop(); recorder.reset(); // You can reuse the object by going back to setAudioSource() step recorder.release(); // Now the object cannot be reused recording = false; notificationTV.setText("Recording stopped!"); Toast.makeText(getApplicationContext(), "Recording stopped!", Toast.LENGTH_LONG).show(); addRecordingToMediaLibrary(); } }); playB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(audiofile == null){ Toast.makeText(getApplicationContext(), "Not recorded yet!", Toast.LENGTH_LONG).show(); return; } MediaPlayer mp=new MediaPlayer(); try{ mp.setDataSource(audiofile.getAbsolutePath());//Write your location here mp.prepare(); mp.start(); }catch(Exception e){ Toast.makeText(getApplicationContext(), "Problem occurred while playing!", Toast.LENGTH_LONG).show(); } } }); getExternalStorageWritePermission(); getAudioRecordPermission(); } protected void addRecordingToMediaLibrary() { //creating content values of size 4 ContentValues values = new ContentValues(4); long current = System.currentTimeMillis(); values.put(MediaStore.Audio.Media.TITLE, audiofile.getName()); values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000)); values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/amr"); values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath()); //creating content resolver and storing it in the external content uri ContentResolver contentResolver = getContentResolver(); Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri newUri = contentResolver.insert(base, values); //sending broadcast message to scan the media file so that it can be available sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)); Toast.makeText(this, "File Added to Media Library" + newUri, Toast.LENGTH_LONG).show(); } private void getExternalStorageWritePermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ // Should we show an explanation? if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { //Requesting permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } } } } private void getAudioRecordPermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){ // Should we show an explanation? if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { } else { //Requesting permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1); } } } } @Override //Override from ActivityCompat.OnRequestPermissionsResultCallback Interface public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission granted } return; } } } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177 package com.zatackcoder.audiorecorder; import android.Manifest;import android.content.ContentResolver;import android.content.ContentValues;import android.content.Intent;import android.content.pm.PackageManager;import android.media.MediaPlayer;import android.media.MediaRecorder;import android.net.Uri;import android.os.Build;import android.os.Environment;import android.provider.MediaStore;import android.support.v4.app.ActivityCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import java.io.File;import java.io.IOException; public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { TextView notificationTV; Button startB; Button stopB; Button playB; MediaRecorder recorder; File audiofile; Boolean recording = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); notificationTV = (TextView)findViewById(R.id.notificationTV); startB = (Button)findViewById(R.id.startB); stopB = (Button)findViewById(R.id.stopB); playB = (Button)findViewById(R.id.playB); startB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(recording){ Toast.makeText(getApplicationContext(), "Already recording stop first", Toast.LENGTH_LONG).show(); return; } recorder = new MediaRecorder(); try { audiofile = File.createTempFile("sound", ".amr", Environment.getExternalStorageDirectory()); } catch (IOException e) { e.printStackTrace(); } recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); Toast.makeText(getApplicationContext(), audiofile.getAbsolutePath(), Toast.LENGTH_LONG).show(); try { recorder.prepare(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); return; } recorder.start(); // Recording is now started recording = true; notificationTV.setText("Recording..."); Toast.makeText(getApplicationContext(), "Recording started!", Toast.LENGTH_LONG).show(); } }); stopB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!recording){ Toast.makeText(getApplicationContext(), "Recording not started yet!", Toast.LENGTH_LONG).show(); return; } recorder.stop(); recorder.reset(); // You can reuse the object by going back to setAudioSource() step recorder.release(); // Now the object cannot be reused recording = false; notificationTV.setText("Recording stopped!"); Toast.makeText(getApplicationContext(), "Recording stopped!", Toast.LENGTH_LONG).show(); addRecordingToMediaLibrary(); } }); playB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(audiofile == null){ Toast.makeText(getApplicationContext(), "Not recorded yet!", Toast.LENGTH_LONG).show(); return; } MediaPlayer mp=new MediaPlayer(); try{ mp.setDataSource(audiofile.getAbsolutePath());//Write your location here mp.prepare(); mp.start(); }catch(Exception e){ Toast.makeText(getApplicationContext(), "Problem occurred while playing!", Toast.LENGTH_LONG).show(); } } }); getExternalStorageWritePermission(); getAudioRecordPermission(); } protected void addRecordingToMediaLibrary() { //creating content values of size 4 ContentValues values = new ContentValues(4); long current = System.currentTimeMillis(); values.put(MediaStore.Audio.Media.TITLE, audiofile.getName()); values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000)); values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/amr"); values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath()); //creating content resolver and storing it in the external content uri ContentResolver contentResolver = getContentResolver(); Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri newUri = contentResolver.insert(base, values); //sending broadcast message to scan the media file so that it can be available sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)); Toast.makeText(this, "File Added to Media Library" + newUri, Toast.LENGTH_LONG).show(); } private void getExternalStorageWritePermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ // Should we show an explanation? if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { //Requesting permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } } } } private void getAudioRecordPermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){ // Should we show an explanation? if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { } else { //Requesting permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1); } } } } @Override //Override from ActivityCompat.OnRequestPermissionsResultCallback Interface public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission granted } return; } } }} Screen Shot Download Android Studio Project AudioRecorder 1 file(s) 6.96 MB Download