Android record audio

Android allows you to integrate audio recording functionality to you applications simply. In this Android, I am going to show you how to record audio from your phone using MediaRecorder, and play the audio using MediaPlayer. In the example application below, while you are recording the audio, the update time is displayed in a TextView. A SeekBar is displayed the time progress while the audio is playing.
To record the audio, first you need to create an instance of MediaRecorder class. Before calling the start() method to start a recording task, you initialize audio source (e. g. AudioSource.MIC), specify output format (e.g. OutputFormat.THREE_GPP), and set the output file name to store the audio. To stop the recording task, you call the stop() followed by the release() method to release the resource.
To play the audio, you create an instance of MediaPlayer class, specify its data source, prepare, and start it. While the audio is playing, you can use Handler to display the time progress on a SeekBar or ProgressBar.

Now to have an example application on audio recording, you create a new Android project. Then add a SeekBar, a TextView, and two Buttons to the activity_main.xml file.



<LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android"
   xmlns:tools=" http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.andexample.MainActivity"
   android:orientation="vertical"
   >
<SeekBar
        android:id="@+id/seek1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:max="100"
        android:progress="0"
         
        
        />
  <TextView
     android:id="@+id/txttime"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_margin="10dp"
     android:textSize="20sp"
     android:textColor="#ff1100"  
     />
  <Button
     android:id="@+id/tbrecord"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Start recording"
     android:onClick="startRecording"   
    
     />
  <Button
     android:id="@+id/tbstop"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"    
     android:text="Stop recording and Play it"
     android:onClick="stopRecording"
     />

</LinearLayout>


Next, in the MainActivity class, you write code to record and play the audio file as shown below.

package com.example.andexample;
import java.io.IOException;
import android.support.v7.app.ActionBarActivity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
Handler handler;
TextView tv;
MediaRecorder mRecorder;
String fileName;
Boolean isRecording;
int recordTime,playTime;
SeekBar seekBar;
MediaPlayer mPlayer;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     tv=(TextView)findViewById(R.id.txttime);
     seekBar=(SeekBar)findViewById(R.id.seek1);
     handler=new Handler();
     fileName=Environment.getExternalStorageDirectory()+ "/audio"+System.currentTimeMillis()+".3gp";
     isRecording=false;
  
    
   }
  
   public void startRecording(View view){
   if(!isRecording){
   //Create MediaRecorder and initialize audio source, output format, and audio encoder
     mRecorder = new MediaRecorder();
      mRecorder.setAudioSource( MediaRecorder.AudioSource.MIC);
      mRecorder.setOutputFormat( MediaRecorder.OutputFormat.THREE_GPP);
      mRecorder.setOutputFile(fileName);
      mRecorder.setAudioEncoder( MediaRecorder.AudioEncoder.AMR_NB);
      // Starting record time
      recordTime=0;
      // Show TextView that displays record time
      tv.setVisibility(TextView.VISIBLE);
      try {
         mRecorder.prepare();
      } catch (IOException e) {
         Log.e("LOG_TAG", "prepare failed");
      }
       // Start record job
       mRecorder.start();
       // Change isRecroding flag to true
       isRecording=true;
       // Post the record progress
       handler.post(UpdateRecordTime);
   }
   }
   public void stopRecording(View view){
   if(isRecording){
   // Stop recording and release resource
   mRecorder.stop();
   mRecorder.release();
   mRecorder = null;
   // Change isRecording flag to false
   isRecording=false;
   // Hide TextView that shows record time
   tv.setVisibility(TextView.GONE);
   playIt(); // Play the audio
   }
   }
  
   public void playIt(){
   // Create MediaPlayer object
   mPlayer = new MediaPlayer();
   // set start time
   playTime=0;
   // Reset max and progress of the SeekBar
   seekBar.setMax(recordTime);
   seekBar.setProgress(0);
     try {
     // Initialize the player and start playing the audio
        mPlayer.setDataSource(fileName);
        mPlayer.prepare();
        mPlayer.start();
        // Post the play progress
        handler.post(UpdatePlayTime);
     } catch (IOException e) {
        Log.e("LOG_TAG", "prepare failed");
     }
   }
  
   Runnable UpdateRecordTime=new Runnable(){
     public void run(){
     if(isRecording){
      tv.setText(String.valueOf(recordTime));    
      recordTime+=1;
      // Delay 1s before next call     
      handler.postDelayed(this, 1000);
      }
      }
     };
   Runnable UpdatePlayTime=new Runnable(){
       public void run(){
       if(mPlayer.isPlaying()){
        tv.setText(String.valueOf(playTime));
        // Update play time and SeekBar
        playTime+=1;              
        seekBar.setProgress(playTime);
        // Delay 1s before next call
        handler.postDelayed(this, 1000);
        }
        }
       };
  
  
}


Finally, in AndroidManifest.xml file, you add two permissions to write data to external storage and to record audio on an Android device.

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


Android-record-audio

Posted by: Dara | post date: 11-17-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.