We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi. I'm trying to make a program that plays the exact opposite of a sound wave. But before that, I need to learn how to properly access the microphone. Here's the sketch I'm trying:
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);
bufferSize = buflen * 2;
audioRecord = new AudioRecord(src, freq, chan, enc, buflen);
println(audioRecord);
audioRecord.startRecording();
buffer = new short[bufferSize];
}
void draw() {
background(200);
audioRecord.read(buffer, 0, bufferSize);
volume = abs(buffer[0]);
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;
}
But when I tried it, I got this exeption:
ION: Animation Thread
Process: processing.test.sketch_171211c, PID: 11072
java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
at android.media.AudioRecord.startRecording(AudioRecord.java:905)
at processing.test.sketch_171211c.sketch_171211c.setup(sketch_171211c.java:47)
at processing.core.PApplet.handleDraw(Unknown Source)
at processing.core.PSurfaceNone.callDraw(Unknown Source)
at processing.core.PSurfaceNone$AnimationThread.run(Unknown Source)
How should I fix it?
I am running a BLU phone.
Answers
@KTibow===
Are you ok with permissions?
try to verify that your audiobuffer length is not <0 (use try catch for that)
try to add some condition boolean before start recording (the audioRecord class has constant for that)
something like: if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {"notReady"=true}
Okay, I'll look at my permissions. And I'll see what else there might be.