Recording audio is not something that you do that often. You might be building just a simple audio note taker or you might be doing something with voice recognition and you’re sending the recorded audio to a server to process it. Either way, you’re going to need to know how to record audio. Recording audio uses the same class as recording video – MediaRecorder. Because of that the process of recording video does not differ a lot from recording audio. You should know that requesting permission for recording media is a dangerous position, because the recordings can be used to spy on the users.
Request Permission For Recording Audio
As I said, recording audio is a dangerous permission so be carefull. This is not meant to be used for spying or anything else malicious. To request permission for recording audio simply add this to your manifest file:
Setting Up The Audio Recorder
First of all, you’re going to need to initialize the MediaRecorder class. These are the most basic methods needed to set up an audio recorder:
Let’s go over these methods one by one. Creating an instance of the MediaRecorder class is extremely simple. It does not require any parameters.
setAudioSource() sets the device from which you’re gonna be recording. In this case, we’re using your phone’s microphone. When you’re testing the app, be sure tp use a real Androi device as the emulators can not record audio.
setOutputFormat() sets the format of your audio file. For a list of available formats go to MediaRecorder.OutputFormat.
setOutputFile() sets the name of your file.
setAudioEncoder() sets the encoder of your audio file. For a list of available encoders go to MediaRecorder.AudioEncoder.
To start recording you’re going to need only two method calls. Those will look like this:
The prepare() method throws an IOException so this bit of the code needs to be in a try block. Other than that it’s fairly straightforward.
Stopping the recording requires a little bit more work. To start recording you needed to add two lines of code, and to stop recording you’re gonna need to add three lines of code. Those are:
I believe that this bit of code needs no explanation. You stop the recording and release the MediaRecorder. If you wanted to build a really simple app you could reduce this just to mediaRecorder.stop(), but this is the minimal amount I believe any app should have to record audio. Also your recording process can be really complicated, but this is the bare minimum I believe you should know.