Android使用AudioRecord判断是否有音频输入
android党都应该玩过一个叫吹裙子的游戏,这个游戏就是原理就是通过监听用户吹出的气的力度来决定如何把mm的裙子弄飞起来的,所以关键在于如何判断用户吹气的力度问题。现在公司刚好有这个需求要评估就是需要一直监听用户的语音输入,当在两秒内没有语音输入时候就暂停某项事情,有语音输入的时候就要继续做某件事。其实这两件事情的本质原理是一样的,就是通过这audiorecord来处理用户输入的原始音频数据,从而计算出当前用户输入的音量大小来判断用户是否有语音输入。下面贴上一段代码用户可以自行研究。
public static int calculatevolume(byte[] var0, int var1) { int[] var3 = null; int var4 = var0.length; int var2; if(var1 == 8) { var3 = new int[var4]; for(var2 = 0; var2 < var4; ++var2) { var3[var2] = var0[var2]; } } else if(var1 == 16) { var3 = new int[var4 / 2]; for(var2 = 0; var2 < var4 / 2; ++var2) { byte var5 = var0[var2 * 2]; byte var6 = var0[var2 * 2 + 1]; int var13; if(var5 < 0) { var13 = var5 + 256; } else { var13 = var5; } short var7 = (short)(var13 + 0); if(var6 < 0) { var13 = var6 + 256; } else { var13 = var6; } var3[var2] = (short)(var7 + (var13 << 8)); } } int[] var8 = var3; if(var3 != null && var3.length != 0) { float var10 = 0.0f; for(int var11 = 0; var11 < var8.length; ++var11) { var10 += (float)(var8[var11] * var8[var11]); } var10 /= (float)var8.length; float var12 = 0.0f; for(var4 = 0; var4 < var8.length; ++var4) { var12 += (float)var8[var4]; } var12 /= (float)var8.length; var4 = (int)(math.pow(2.0d, (double)(var1 - 1)) - 1.0d); double var14 = math.sqrt((double)(var10 - var12 * var12)); int var9; if((var9 = (int)(10.0d * math.log10(var14 * 10.0d * math.sqrt(2.0d) / (double)var4 + 1.0d))) < 0) { var9 = 0; } if(var9 > 10) { var9 = 10; } return var9; } else { return 0; } }
上述方法的形参中的一个字节数组便是当前捕捉到用户输入的原始音频数据,第二个形参则是音频数据格式位pcm,16位每个样本,比如如果音频数据格式设为audioformat.encoding_pcm_16bit,则参数传16。最后实现的效果就是如下:
01-12 18:54:17.222 e/recordtest(24249): no voice input
…………….
01-12 18:54:19.027 e/recordtest(24249): no voice input
01-12 18:54:19.067 e/recordtest(24249): no voice input
01-12 18:54:19.105 e/recordtest(24249): no voice input
01-12 18:54:19.145 e/recordtest(24249): no voice input
01-12 18:54:19.188 e/recordtest(24249): no voice input
01-12 18:54:19.227 e/recordtest(24249): no voice input
01-12 18:54:19.228 e/recordtest(24249): no voice input in 2 sec
01-12 18:54:19.269 e/recordtest(24249): no voice input
01-12 18:54:19.306 e/recordtest(24249): no voice input
01-12 18:54:19.345 e/recordtest(24249): no voice input
01-12 18:54:19.387 e/recordtest(24249): no voice input
01-12 18:54:19.427 e/recordtest(24249): no voice input
01-12 18:54:19.466 e/recordtest(24249): has voice input
01-12 18:54:19.505 e/recordtest(24249): has voice input
01-12 18:54:19.546 e/recordtest(24249): has voice input
01-12 18:54:19.586 e/recordtest(24249): has voice input
01-12 18:54:19.646 e/recordtest(24249): has voice input
01-12 18:54:19.686 e/recordtest(24249): has voice input
01-12 18:54:19.726 e/recordtest(24249): has voice input
01-12 18:54:19.766 e/recordtest(24249): has voice input
以上所述是小编给大家介绍的android使用audiorecord判断是否有音频输入,多条目的实例代码,希望对大家有所帮助