I'm trying to record audio and get the frequencies. I can successfully do so with a sampling rate of 44100 and a block size of 2048. The bin size is around 20, I believe. However, if I try to increase the block size to 4096, then rather than get accurate frequencies, I just get the same inaccurate frequency back, with no magnitude/decibels.
My recording task is as follows:
private class RecordAudio extends AsyncTask<Void, double[], Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
audioRecord = new AudioRecord(
MediaRecorder.AudioSource.DEFAULT, frequency,
channelConfiguration, audioEncoding, bufferSize);
int bufferReadResult;
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
try {
audioRecord.startRecording();
} catch (IllegalStateException e) {
Log.e("Recording failed", e.toString());
}
while (started) {
if (isCancelled() || (CANCELLED_FLAG == true)) {
started = false;
//publishProgress(cancelledResult);
Log.d("doInBackground", "Cancelling the RecordTask");
break;
} else {
bufferReadResult = audioRecord.read(buffer, 0, blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
toTransform[i] = (double) buffer[i] / 32768.0; // signed 16 bit
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
}
return true;
}
@Override
protected void onProgressUpdate(double[]...progress) {
int mPeakPos = 0;
double mMaxFFTSample = 150.0;
for (int i = 100; i < progress[0].length; i++) {
int x = i;
int downy = (int) (150 - (progress[0][i] * 10));
int upy = 150;
//Log.i("SETTT", "X: " + i + " downy: " + downy + " upy: " + upy);
if(downy < mMaxFFTSample)
{
mMaxFFTSample = downy;
mMag = mMaxFFTSample;
mPeakPos = i;
}
}
mFreq = (((1.0 * frequency) / (1.0 * blockSize)) * mPeakPos)/2;
//Log.i("SSS", "F: " + mFreq + " / " + "M: " + mMag);
Log.i("SETTT", "FREQ: " + mFreq + " MAG: " + mMaxFFTSample);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
try{
audioRecord.stop();
}
catch(IllegalStateException e){
Log.e("Stop failed", e.toString());
}
}
}
Hoping there is a quick fix I'm missing. Thanks.