8 Oct 2012

Audio Recorder in Android.

The android.media.AudioRecord class manages the audio resources for Java applications to record audio from the audio input hardware of the platform.



record.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="HB-Record Audio" />

    <Button
        android:id="@+id/startrec"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Recording" />

    <Button
        android:id="@+id/stoprec"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Stop Recording" />

    <Button
        android:id="@+id/playback"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play Back" />

</LinearLayout>


AndroidAudioRecordActivity:

public class AndroidAudioRecordActivity extends Activity
{

      Button startRec, stopRec, playBack;
      Boolean recording;
     
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.record);
           
            startRec = (Button)findViewById(R.id.startrec);
            stopRec = (Button)findViewById(R.id.stoprec);
            playBack = (Button)findViewById(R.id.playback);

            startRec.setOnClickListener(startRecOnClickListener);
            stopRec.setOnClickListener(stopRecOnClickListener);
            playBack.setOnClickListener(playBackOnClickListener);

      }

      OnClickListener startRecOnClickListener   = new OnClickListener()
      {
            @Override
            public void onClick(View arg0)
            {
                  Thread recordThread = new Thread(new Runnable()
                  {
                        @Override
                        public void run()
                        {
                              recording = true;
                              startRecord();
                        }

                  });

                  recordThread.start();
            }};

            OnClickListener stopRecOnClickListener = new OnClickListener()
            {
                  @Override
                  public void onClick(View arg0)
                  {
                        recording = false;
                  }};

                  OnClickListener playBackOnClickListener   = new OnClickListener()
                  {

                        @Override
                        public void onClick(View v)
                        {
                              playRecord();
                        }

                  };

                  private void startRecord()
                  { 
                        File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");

                        try
                        {
                              file.createNewFile();

                              OutputStream outputStream = new FileOutputStream(file);
                              BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
                              DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);

                              int minBufferSize = AudioRecord.getMinBufferSize(11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT);

                              short[] audioData = new short[minBufferSize];

                              AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                          11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT,
                                          minBufferSize);

                              audioRecord.startRecording();

                              while(recording)
                              {
                                    int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
                                    for(int i = 0; i < numberOfShort; i++)
                                    {
                                          dataOutputStream.writeShort(audioData[i]);
                                    }
                              }
                              audioRecord.stop();
                              dataOutputStream.close();

                        }
                        catch (IOException e)
                        {
                              e.printStackTrace();
                        }

                  }

                  void playRecord()
                  {
                        File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");

                        int shortSizeInBytes = Short.SIZE/Byte.SIZE;

                        int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes);
                        short[] audioData = new short[bufferSizeInBytes];

                        try {
                              InputStream inputStream = new FileInputStream(file);
                              BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                              DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);

                              int i = 0;
                              while(dataInputStream.available() > 0)
                              {
                                    audioData[i] = dataInputStream.readShort();
                                    i++;
                              }

                              dataInputStream.close();

                              AudioTrack audioTrack = new AudioTrack(
                                          AudioManager.STREAM_MUSIC,
                                          11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT,
                                          bufferSizeInBytes,
                                          AudioTrack.MODE_STREAM);

                              audioTrack.play();
                              audioTrack.write(audioData, 0, bufferSizeInBytes);


                        } catch (FileNotFoundException e)
                        {
                              e.printStackTrace();
                        } catch (IOException e)
                        {
                              e.printStackTrace();
                        }
                  } 
}

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

Click here for more ref Link:

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)

Wake lock in Android.

Its use for control of the power state of the device.
Device battery life will be significantly affected by the use of this API. Do not acquire WakeLocks unless you really need them, use the minimum levels possible, and be sure to release it as soon as you can.

To prevent lock while running the application can be done two ways.
1.PowerManager
2. WindowManager:  Using Power Manager is not a good way. They easily drain battery. So using Window Manager we can avoid the screen locking while application is running. Add the below snippet in your activity to avoid screen lock:  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
No permissions required while you used Window Manager. 


*Using Power Manager*

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.os.PowerManager;
import android.view.WindowManager;
public class AutoLock extends Activity
{
      PowerManager pm;
      PowerManager.WakeLock wl;
      public void WACK_LOCAK_Declare()
      {
      pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
      wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"MyWakeLock");
      }
      public void WACK_LOCAK_Acquire()
      {
            wl.acquire();
      }
      public void WACK_LOCAK_Release()
      {
            wl.release();
      }
} 

Permission:
<uses-permission android:name="android.permission.WAKE_LOCK" />



I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)