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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
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
Comments