Solved: How to use Microphone on Android

edited November 2013 in Android Mode

After seeing the post of lognaturel about Microphone on Android I have made few modifications to the code and make it work on my Samsung Galaxy Y with the Processing IDE 2.0.3. (ONLY WORKS IN PORTRAIT MODE) and this is my code:

//  WARNING! Be sure that your Sketch have active this permissions:
//    RECORD_AUDIO
//    WRITE_EXTERNAL_STORAGE    

import android.app.Activity;
import android.os.Bundle;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

    short[] buffer = null;
    AudioRecord audioRecord = null;
    int bufferSize= 1024;
    float volume = 0;
    int buflen;

    void setup() {

        orientation(PORTRAIT);
        int freq =44100;
        int chan = AudioFormat.CHANNEL_IN_MONO;
        int enc  = AudioFormat.ENCODING_PCM_16BIT;
        int src  = MediaRecorder.AudioSource.MIC;
        buflen = AudioRecord.getMinBufferSize(freq, chan, enc);
        audioRecord = new AudioRecord(src,freq,chan,enc,buflen);

        audioRecord.startRecording();
        buffer = new short[bufferSize];
    }

    void draw() {
       background(200);

       int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
       volume = 100;
       for (int i = 0; i < bufferReadResult; i++) {
          volume = Math.max(Math.abs(buffer[i]), volume);
       }
       text("" + volume, 100, 100);
       //draw a box if you blow the mic
       if(volume>300)rect(10,10,20,20);
    }

    void stop() {
      audioRecord.stop();
      audioRecord.release();
      audioRecord = null;
    }

I hope could be of help for all of you.

Answers

Sign In or Register to comment.