2

How to get the amplitude when blowing into MIC in android device.

MediaRecorder recorder = new MediaRecorder();
   recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

   Timer timer = new Timer();
   timer.scheduleAtFixedRate(new RecorderTask(recorder), 0, 1000);

private class RecorderTask extends TimerTask {
private MediaRecorder recorder;

public RecorderTask(MediaRecorder recorder) {
    this.recorder = recorder;
}

public void run() {
    Log.v("", "amplitude is" + recorder.getMaxAmplitude());
}
}

I am getting an error:

ERROR/AndroidRuntime(20927): Caused by: java.lang.RuntimeException: setAudioSource failed.
ERROR/AndroidRuntime(20927): at android.media.MediaRecorder.setAudioSource(Native Method)
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
Snagulapati
  • 31
  • 1
  • 1
  • 3

3 Answers3

9
public boolean isBlowing()
    {
        boolean recorder=true;

        int minSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        AudioRecord ar = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,minSize);


        short[] buffer = new short[minSize];

        ar.startRecording();
        while(recorder)
        {

            ar.read(buffer, 0, minSize);
            for (short s : buffer) 
            {
                if (Math.abs(s) > 27000)   //DETECT VOLUME (IF I BLOW IN THE MIC)
                {
                    blow_value=Math.abs(s);
                    System.out.println("Blow Value="+blow_value);
                    ar.stop();
                    recorder=false;

                    return true;

                }

            }
        }
        return false;

    }
Bill Mote
  • 12,644
  • 7
  • 58
  • 82
Rajeev
  • 111
  • 1
  • 3
2

You need to set up permissions on your manifest file

 <uses-permission android:name="android.permission.RECORD_AUDIO" />
Paranoid Android
  • 4,672
  • 11
  • 54
  • 73
0

You have to initialize the recorder, as well as set several methods. Look at the documentation for MediaRecorder to see how to do this. I've used this method and it works quite well.

Nicholas
  • 7,403
  • 10
  • 48
  • 76