Capturing audio in Android

In this post I am going to show how to capture audio in Android.
Android allows to capture audio in very easy manner. But today I spent 3 hours for creating working example. I don’t know why I spent so much time,maybe because it is first time when I tried to work with multimedia in Android. Anyway now I know how it works and I want to share my knowledge. Here I am going to record/capture audio from phone’s/emulator’s microphone to the SDCard (Note:I used web camera’s microphone for recording audio –it works).
For capturing audio from program need to do:

  • Add permission to AndroidManifest.xml
  • Create an instance of MediaRecorder
  • Create an instance of ContentValues,and add properties
    like TITLE,TIMESTAMP,and the all-important MIME_TYPE
  • Create a file path for the data to go to using ContentResolver
  • Set the source for audio,using MediaRecorder.setAudioSource()
  • Set output file format using MediaRecorder.setOutputFormat()
  • Set your encoding for audio,using MediaRecorder.setAudioEncoder()
  • Use prepare() and start() to prepare and start your recordings
  • Use stop() and release() to gracefully stop and clean up your recording
    process

As you can see it is simple. And I want to show full example which shows that practice is easy as the theory.
Example:

import java.io.File;import android.app.Activity;import android.content.ContentResolver;import android.content.ContentValues;import android.content.Intent;import android.media.MediaRecorder;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.provider.MediaStore;import android.provider.MediaStore.MediaColumns;import android.util.Log;import android.view.View;import android.widget.Button;public class Main extends Activity{private MediaRecorder mediaRecorder;private File file = null;static final String PREFIX = "record";static final String EXTENSION = ".3gpp";@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mediaRecorder = new MediaRecorder();Button startRecording = (Button) findViewById(R.id.startBtn);Button stopRecording = (Button) findViewById(R.id.stopBtn);startRecording.setOnClickListener(new View.OnClickListener(){public void onClick(View v){try{startRecording()} catch (Exception e){e.printStackTrace()}}});stopRecording.setOnClickListener(new View.OnClickListener(){public void onClick(View v){stopRecording();saveToDB()}})}private void startRecording() throws Exception{mediaRecorder = new MediaRecorder();mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);if (file == null){File rootDir = Environment.getExternalStorageDirectory();file = File.createTempFile(PREFIX,EXTENSION,rootDir)}mediaRecorder.setOutputFile(file.getAbsolutePath());mediaRecorder.prepare();mediaRecorder.start()}private void stopRecording(){mediaRecorder.stop();mediaRecorder.release()}private void saveToDB(){ContentValues values = new ContentValues(3);long current = System.currentTimeMillis();values.put(MediaColumns.TITLE,"My Audio record");values.put(MediaColumns.DATE_ADDED,(int) (current / 1000));values.put(MediaColumns.MIME_TYPE,"audio/mp3");values.put(MediaColumns.DATA,file.getAbsolutePath());ContentResolver contentResolver = getContentResolver();Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;Uri newUri = contentResolver.insert(base,values);sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,newUri))}}

Note:need to add to AndroidManifest.xml these permissions

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

After running this application you should see something like this on DDMS perspective ->File Explorer view -> sdcard:
Recorded file
Okay. In this example you can see 3 methods which are interesting for us.
I will explain very short these methods. I don’t think that after reading this code you will have some critical questions.

startRecording()

In this method we create MediaRecorder object and after that we set audio sourcemicrophone,audio output format3gpp,audio encoderAMR (Narrowband) audio codec,output fileon SDCard and finally we start recording (don’t forget about prepare() method).

stopRecording()

This method very short. In this method we call stop() and release() methods.

saveToDB()

In this method we set all data about new recorded file:title,creation date,mime type and file location.
Also we add notification for Media player about this file.
Last point is very useful,because after capturing we can open our record by visiting:
Android application ->Music ->Playlists tab ->Recently added ->My Audio record.
Note:in emulator I had problem with playing,but in phone it works correct.
Music
That’s all what I wanted to show you in this post.

 

Download code from this post.

 

If you’d like to get the latest posts as soon as they’re published,subscribe to our feed!

Share

No related posts.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.