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判断是否有音频输入,多条目的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!