Tuesday, September 6, 2011

Android MediaRecorder Example


The android.media package contains classes to interact with the media subsystem. The android.media.MediaRecorder class is used to take samples of media, including audio and video. The MediaRecorder operates as a state machine. You need to set various parameters, such as source device and format. Once set, the recording may begin for an arbitrary amount of time until subsequently stopped.
The code shown does not include the UI elements of the application (see download for the full source code).
MediaRecorder mrec ;
File audiofile = null;
private static final String TAG="SoundRecordingDemo";
protected void startRecording() throws IOException 
{
   mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
   mrec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
   mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
   if (mSampleFile == null) 
   {
       File sampleDir = Environment.getExternalStorageDirectory();
       try 
       { 
          audiofile = File.createTempFile("ibm", ".3gp", sampleDir);
       }
       catch (IOException e) 
       {
           Log.e(TAG,"sdcard access error");
           return;
       }
   }
   mrec.setOutputFile(audiofile.getAbsolutePath());
   mrec.prepare();
   mrec.start();
}
protected void stopRecording() 
{
   mrec.stop();
   mrec.release();
   processaudiofile(audiofile.getAbsolutePath());
}
protected void processaudiofile() 
{
   ContentValues values = new ContentValues(3);
   long current = System.currentTimeMillis();
   values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
   values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
   values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
   values.put(MediaStore.Audio.Media.DATA, audiofile.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));
}

In the startRecording method, an instance of a MediaRecorder is instantiated and initialized:
  • The input source is set to the microphone (MIC).
  • The output format is set to 3GPP (*.3gp files), which is a media format geared toward mobile devices.
  • The encoder is set to the AMR_NB, which is an audio format, sampling at 8 KHz. The NB is for narrow band
The audio file is stored on the storage card, rather than in internal memory. External.getExternalStorageDirectory()returns the name of the storage card location, and a temporary file name is created in that directory. This file is then associated with the MediaRecorder instance by a call to the setOutputFile method. The audio data will be stored in this file.
The prepare method is invoked to finalize the initialization of the MediaRecorder. When you're ready to commence the recording process, the start method is called. Recording takes place to the file on the storage card until the stop method is invoked. The release method frees resources allocated to the MediaRecorder instance.
Once the audio sample has been taken, there are a few actions that can take place:
  • Add the audio to the media library on the device.
  • Perform some pattern recognition steps to identify the sound:
    • Is this the baby crying?
    • Is this the owner's voice, and should we unlock the phone?
    • Is this the "open-sesame" phrase that unlocks the door to the secret entrance?
  • Automatically upload the audio file to a network location for processing.
In the code sample, the processaudiofile method adds the audio to the media library. An Intent is used to notify the on-device media application that new content is available.
One final note about this snippet of code: If you try it, it won't record the audio at first. You will see a file created, but there will be no audio. You need to add a permission to the AndroidManifest.xml file:
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

At this point, you've learned a bit about interacting with Android sensors and recording audio. The next section takes a broader view of application architecture related to data gathering and reporting systems.

1 comment:

  1. In line 9 you use mSampleFile, but you have never declared it.

    ReplyDelete