In this tutorial, I'll be making a UI with a start/stop recording button. I am using MediaRecording class to record the audio.
After making the layout, Call the method below on click of the mike button in the respective class:
MediaRecorder recorder;
boolean isRecording = false;
recordAudio()
{
if(isRecording==true)
{
isRecording = false;
stopRecording();
mike_btn.setText("Start recording");
}
else
{
mike_btn.setText("Stop recording");
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "/files/");
path.mkdirs();
try
{
audioFile = File.createTempFile("TestSound", ".amr", path);
recorder.setOutputFile(audioFile.getAbsolutePath());
recorder.prepare();
}
catch (Exception e)
{
throw new RuntimeException(
"IOException on MediaRecorder.prepare", e);
}
recorder.start();
isRecording = true;
}
}
/**
* This method stop audio recording and release resources
*/
private void stopRecording()
{
isRecording = false;
if (recorder != null)
{
recorder.stop();
recorder.release();
recorder = null;
}
}
Also, add following permissions in the manifest file:
android:name="android.permission.RECORD_AUDIO"
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
That's all and just simple to record an audio.
Hope you find this helpful :)
0 Comment(s)