13 - Phonegap Multimedia - Record Audio on the Device

Introduction

PhoneGap’s Media API offers methods to record audio on the mobile device. In fact, we can control HTML5 media elements (<audio> and <video>) with the help of JavaScript. But for recording audio, we cannot use these elements with the help of JavaScript because here we need to interact with the hardware, a microphone. In other words, we cannot avoid PhoneGap framework when the app has to interact with the hardware.

We will be using the startRecord and stopRecord methods of the Media API to start and stop recording. Once you are done with the recording, you could find the recorded audio file in the same simulator on which you run the app. But the issue here is that audio recording does not work uniformly in all devices. So, the code you write to record audio in an Android device might not work in some other device like BlackBerry or iOS. In this tutorial, we are going to create an Android app for audio recording.

Create an App for Audio Recording

Create a mobile app named AndroidRecordAudio for Android platform. Once the project is created on the desktop, bring the project into the Android Development Environment (Eclipse).

We need to provide specific permissions to access this feature. For that, open the AndroidManifest.xml file using your favourite text editor. Now add the following lines of code.

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Save the AndroidManifest.xml file. Open the index.html file in the assets/www folder using your text editor and clean it up. Change the title to “Audio Recording”.

Next we are going to add two buttons, one to start recording and the other to stop recording. So, add the following lines of code inside the <body> section of index.html file.

<button id="btnStart">Start Recording</button>
<button id="btnStop">Stop Recording</button>

Add the following lines of code inside the <head> section to check whether the device is ready. Once the device is ready, we will add the event listeners for the two buttons for their click events.

<script>
        window.onload = function()
        {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        function onDeviceReady()
        {
            document.getElementById("btnStart").addEventListener('click', startRecording, false);
            document.getElementById("btnStop").addEventListener('click', stopRecording, false);
        }
</script>

Next we need to write the startRecording and stopRecording functions. Inside the startRecording function, we will create a Media object. But the thing is that we will have to use this media object both in startRecording and in stopRecording functions. So, declare a variable named myMedia with global scope. Add the following line of code just after the opening <script> tag.

       var myMedia;

Add the following lines of code after the onDeviceReady function.

function startRecording()
        {
            var src = "FinalAudio.wav";
            myMedia = new Media(src, onSuccess, onError);
            myMedia.startRecord();
            alert("Started recording");
         }
        function onSuccess() {
            console.log("Created Audio for Recording");
        }
        function onError(error) {
            alert('code: '    + error.code    + '\n' +
                  'message: ' + error.message + '\n');
        }
        function stopRecording()
        {
            myMedia.stopRecord();
            alert("Stopped recording");
        }

We have specified the name of the file as FinalAudio.wav. We have also specified two callback functions onSuccess and onError. Once the recording is started, we are displaying a message "Started recording" to inform the user the current status. Similarly, when the user clicks the Stop Recording button, a message "Stopped recording" is displayed. As you see, we are using startRecord() and stopRecord() methods to start and stop recording. These methods are offered by PhoneGap’s Media API.

Save the index.html file and run the project from Android Development Environment. You will get a screen like this:

out1.png

Now your computer must be connected to a microphone to test this app. Click the Start Recording button and you will get a screen like this:

out2.png

Click the OK button and start speaking. Once you are done, click the Stop Recording button and you will get a screen like this:

out3.png

Click the OK button. Now check for the folder that stores audio files. In my emulator, the name of the folder is Music, it could be different in yours.

out4.png

Double click the folder and you will find the recorded file. In our case, it is FinalAudio.wav (the first item in the following image).

out5.png

All other items you see in the following image are the files I have created using the same app. Just click on the file and you will hear your recorded voice.

out6.png

Yes, we have created a wonderful app that allows you to record audio. You can also include a Play button so that you can listen to your audio soon after recording without checking the location where it has been saved.

Summary

In this tutorial, we have created an Android app that records audio. This code might not work if you try it on an iPhone device. An iPhone device does not create the file for recording (in our case FinalAudio.wav) on its own. You should either already have the file or write the code to create a file using File API of PhoneGap. Moreover, every device and configuration does not support all types of media files. For example, if you specify the name of the file as FinalAudio.mp3 and try to run the app on an Android device of a specific configuration, then recording might not be successful in case if the specific configuration does not support .mp3 files. In short, audio recording does not work uniformly in all devices.

Like us on Facebook