Recording and saving audio

Adding OnClickListeners

First, we need to add OnClickListeners to the buttons to make sure they react to user events. As I mentioned before the check for the right permissions will be added in the OnClickListener call of the start_recording button.

Configuring the MediaRecorder

Next, we need to define a path for our output and start configuring our MediaRecorder.

Here, we get the path to the root of our external storage and add our recording name and filetype to it. After that, we create our MediaRecorder object and define the audio source, audio encoder, output format and output file.

Recording and saving the audio

The code used to start the MediaRecorder is defined in the OnClickListener of the start_recording button.

As you can see we need to call the prepare function before we can start the recording. We also embed it into a try-catch block to make sure the app won’t crash when the prepares function fails.

The OnClickListeners of the stop button is very similar to the one we defined above.

Here we check if the MediaRecorder is currently running before we actually stop the recording because our app would crash if the stop method is called while the MediaRecorder isn’t recording. After that, we change the state variable to false to prevent the user from pressing the stop button again.

After that, we just need to define the OnClickListener for the pause/resume button.

In these two methods we check if the MediaRecorder is running. If so we pause the recording and change the text of the button to resume. If clicked again the recording will resume from the point it left of.

Finally, we can start recording audio and listen to it by opening the recording.mp3 file that will be saved in our local storage.