I want to display the microphone usage status in android. I would like to display when more than a certain decibel. What I can get is raw data in bytes [] and usage time. How can I get a decibel through this?
@Override public void processData(byte[] samples, double streamtimeMill) { super.processData(samples, streamtimeMill); calculatePeakAndRms(encodeToSample(samples,samples.length)); } public short[] encodeToSample(byte[] srcBuffer, int numBytes) { byte[] tempBuffer = new byte[2]; int nSamples = numBytes / 2; short[] samples = new short[nSamples]; // 16-bit signed value for (int i = 0; i < nSamples; i++) { tempBuffer[0] = srcBuffer[2 * i]; tempBuffer[1] = srcBuffer[2 * i + 1]; samples[i] = bytesToShort(tempBuffer); } return samples; } public short bytesToShort(byte [] buffer) { ByteBuffer bb = ByteBuffer.allocate(2); bb.order(ByteOrder.BIG_ENDIAN); bb.put(buffer[0]); bb.put(buffer[1]); return bb.getShort(0); } public void calculatePeakAndRms(short [] samples) { double sumOfSampleSq = 0.0; // sum of square of normalized samples. double peakSample = 0.0; // peak sample. for (short sample : samples) { double normSample = (double) sample / 32767; // normalized the sample with maximum value. sumOfSampleSq += (normSample * normSample); if (Math.abs(sample) > peakSample) { peakSample = Math.abs(sample); } } double rms = 10 * Math.log10(sumOfSampleSq / samples.length); double peak = 20 * Math.log10(peakSample / 32767); Log.v("rms", rms + ""); Log.v("peak", peak + ""); } I tried running this code, but the value printed in rms is between -4 and -9, which doesn't seem to be the actual decibel. Most of the code is described in terms of short [] so it's hard to find my case. How can I change byte[] to decibel?
没有评论:
发表评论