Wednesday, 2 May 2012

Audio Recording in Android


There are many times when we people have to integrate audio recording feature in our application.
It is very easy to implement Just we have to make an Audio Recorder class and call it from our activity as:-



public class AudioRecorderHelper {

MediaRecorder mRecorder = new MediaRecorder();
String path;


public AudioRecorderHelper(String path){

this.path = savePath(path);

}

private String savePath(String path){

if(!path.startsWith("/")){

path = "/" + path;

}

if(!path.contains(".")){
path+= ".3gp";

}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}

public void start() throws IOException{

String state = android.os.Environment.getExternalStorageState();
   if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
       throw new IOException("SD Card is not mounted.  It is " + state + ".");
   }

   // make sure the directory we plan to store the recording in exists
   File directory = new File(path).getParentFile();
   if (!directory.exists() && !directory.mkdirs()) {
     throw new IOException("Path to file could not be created.");
   }

   mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
   mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
   mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
   mRecorder.setOutputFile(path);
   mRecorder.prepare();
   mRecorder.start();
}


public void stop() throws IOException {
   mRecorder.stop();
   mRecorder.release();
 }
}



Call this class and use its start and stop functions on your demand whenever you want.
Try it. The code is complete.