Homesick App — Recording and Storing Audio on Android
Nov 5, 2014
This is part of an ongoing series of posts about Homesick, my bachelor project.
The Android side of the client is hosted here.
I’ve had a small handful of experience in Android development, so I’ve drawn up a simple activity with two buttons for the time being:
Really, truly barebones. :-)
To get going with recording audio, the official API guides from Google were very helpful.
First off, I had to add the microphone and storage permissions to the manifest:
```xml AndroidManifest.xml https://github.com/carmenh/homesick-app/blob/master/app/src/main/AndroidManifest.xml Source <?xml version=”1.0” encoding=”utf-8”?>
When the activity is initialized, it sets up the destination of the recorded audio file on a local variable:
```java RecordingActivity.java https://github.com/carmenh/homesick-app/blob/master/app/src/main/java/com/carmenh/homesick/RecordingActivity.java Source
public RecordingActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
The above gets the location of external storage on the device and then appends the file name. In this case, the example uses ‘audiorecordtest.3gp.’
It then hooks up the buttons to the activity and when the record button is pressed, the following is called:
```java RecordingActivity.java https://github.com/carmenh/homesick-app/blob/master/app/src/main/java/com/carmenh/homesick/RecordingActivity.java Source private void startRecording() { mRecorder = new MediaRecorder(); mRecorder.reset(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(mFileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
} ```
On line 2, we set our local mRecorder to be a new instance of android.media.MediaRecorder. On line 4, we set the audio source to be the device’s microphone. On line 5, we set the format to be 3gp. On line 6, we set the destination to be file path we specified earlier. Then, the Audio Encoder is set. Choices can be found here.
Finally, we call prepare() on it to finalize the recorder object’s settings. Once that succeeds, we call start() to begin the recording process.
Stopping is a much simpler process:
java RecordingActivity.java https://github.com/carmenh/homesick-app/blob/master/app/src/main/java/com/carmenh/homesick/RecordingActivity.java Source
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
And that’s it! With this all set up, the app can record audio and store it in the 3gp file format on the device’s external storage.
Next up, that play button…
Buy me a coffee @hola_soy_milk