我创建了一个示例应用程序,用于通过谷歌搜索等语音命令搜索网络中的任何内容。我用import android.media.AudioRecord;
这个。当用户说我根据声音的强度在图标上显示动画时。为此,我做了一个从互联网上得到的数学计算。如果我在做这个计算,我会得到错误的命令。请帮我找出原因。
请看我的代码。
minBufferSizeInBytes = AudioRecord.getMinBufferSize( 8000,
AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
rec = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, 8192);
//重新编码从这里开始
public void run() {
rec.startRecording();
while (!done) {
int nshorts = readBlock();
if (nshorts <= 0)
break;
}
rec.stop();
rec.release();
}
// readBlock() 方法。计算在这里
int readBlock() {
short[] buf = new short[this.block_size];
byte audioBuffer[] = new byte[this.minBufferSizeInBytes];
float totalAbsValue = 0.0f;
short sample = 0;
int numberOfReadBytes = 0;
float tempFloatBuffer[] = new float[3];
int tempIndex = 0;
int nshorts = rec.read(buf, 0, buf.length);
if (nshorts > 0) {
q.add(buf);
}
numberOfReadBytes = rec.read( audioBuffer, 0,minBufferSizeInBytes );
for( int i=0; i<numberOfReadBytes; i+=2 ) {
sample = (short)( (audioBuffer[i]) | audioBuffer[i + 1] << 8 );
if(sample!=0) {
totalAbsValue += Math.abs( sample ) / (numberOfReadBytes/2);
}
}
tempFloatBuffer[tempIndex%3] = totalAbsValue;
temp = 0.0f;
for( int i=0; i<3; ++i )
temp += tempFloatBuffer[i];
System.out.println("Temp: "+temp);
mMyClass = MyClass.getInstance();
mMyClass.handler.postDelayed(mMyClass.AnimateRunnable, 100);
return nshorts;
}