Homesick App - Recording and Storing Audio on Android

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:

AndroidManifest.xmlSource
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ramonh.homesick" >

    <!-- application content -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

</manifest>

When the activity is initialized, it sets up the destination of the recorded audio file on a local variable:

RecordingActivity.javaSource
1
2
3
4
    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:

RecordingActivity.javaSource
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

RecordingActivity.javaSource
1
2
3
4
5
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…