Android SDK has a lot of possibilities to take profit of the smartphones features. Amongst them, there are the possibilities to record and play audio. In that tutorial, you are going to learn how to create an Audio Recorder on Android by using the MediaRecorder API provided in Android SDK.
Creating the User Interface
First, we need to define the user interface for our Audio Recorder. It consists on a simple layout with 3 buttons : one to start recording audio, the second to stop recording audio and the last to play recorded audio :
Recording and Playing Sounds
Next step is to write the Java code for the Main Activity. First, we connect buttons with the code to react to user events :
We need to disable stop and play button when the activity is created by calling the setEnabled method with false parameter. Then, we need to define a path for the result file of the record. It will be stored in a String variable named outputFile :
Here, we choose to store the file at the root of the external storage directory. Now, it’s time to configure the MediaRecorder object that will let us to record audio :
We define the audio source, the microphone here, the output format, the audio encoder and the output file where the recorded audio will be saved.
The code used to start recording audio is defined into the OnClickListener implementation set for the record button :
Like you can see, before to start recording audio, you must call the prepare method of the MediaRecorder object then you can call the start method.
We make the same thing to set an OnClickListener implementation on the stop button :
Here, we stop to record audio by calling the stop method of the MediaRecorder object. Then, we need to call the release method. Last thing is to manage buttons’ state. We disable the stop button and we enable the record and play buttons. Now, we have a recorded audio file stored at the outputFile path. So, we can play the audio file :
To play the audio file, we are going to use the MediaPlayer API. We create a MediaPlayer instance and we set the path of the audio file to play. Before to play the audio file, we need to call the prepare method of the MediaPlayer object. Finally, we can play the file by calling the start method.
Complete source code for the Main Activity
Like you can see, it’s really simple to create a basic Audio Recorder for Android. Here, you can get the complete source code :
This tutorial is also available in video on YouTube in 2 parts :
- Part 1
- Part 2