本文实例为大家分享了Android实现静音检测的具体代码,供大家参考,具体内容如下
一、背景
做语音评测的时候需要在用户不说话的时候自动停止,这时候就需要判断什么时候不说话处于静音的状态。
二、原理
每次录音的时候可以根据录音的数据计算出音强,设定一个音强值为上限,当音强超过这个值的时候判断为非静音当小于这个值的时候判断为静音,当静音次数连续达到一定的次数的时候就停止录音。
三、代码实现
1.计算音强
public static double calculateVolume(byte[] buffer) {
double sumVolume = 0.0;
double avgVolume = 0.0;
double volume = 0.0;
for (int i = 0; i < buffer.length; i += 2) {
int v1 = buffer[i] & 0xFF;
int v2 = buffer[i + 1] & 0xFF;
int temp = v1 + (v2 << 8);
if (temp >= 0x8000) {
temp = 0xffff - temp;
}
sumVolume += Math.abs(temp);
}
avgVolume = sumVolume / buffer.length / 2;
volume = Math.log10(1 + avgVolume) * 10;
return volume;
}
2.静音检测
class VadManager : VadInterface {
private var mConfig: Config? = null
private var mCount = 0
private var mBeginMuteCount = 0
private var mBeginMuteMaxCount = 9
private var mEndMuteCount = 0
private var mEndMuteMaxCount = 9
companion object {
const val RECORD_DATA_TIME = 200
const val MUTE_VOLUME = 18.0
@Volatile
private var instance: VadInterface? = null
@JvmStatic
fun getInstance(): VadInterface {
if (instance == null) {
synchronized(VadManager::class.java) {
if (instance == null) {
instance = VadManager()
}
}
}
return instance!!
}
}
override fun startVad(config: Config?) {
mConfig = config
mConfig?.let {
if (it.vadEnable) {
if (it.vadBos > 0) {
mBeginMuteMaxCount = it.vadBos / RECORD_DATA_TIME
}
if (it.vadEos > 0) {
mEndMuteMaxCount = it.vadEos / RECORD_DATA_TIME
}
}
}
}
override fun canStopRecord(volume: Double): Boolean {
L.i("volume", volume.toString())
mCount++
mConfig?.let {
if (!it.vadEnable) {
return false
}
if (mCount <= mBeginMuteMaxCount) {
//前端点连续静音计数
if (volume <= MUTE_VOLUME) {
mBeginMuteCount++
} else {
mBeginMuteCount = 0
}
} else if (mCount == mBeginMuteMaxCount + 1) {
//判断是否达到前端点最大静音次数
if (mBeginMuteCount >= mBeginMuteMaxCount) {
closeVad()
return true
}
} else {
//后端点连续静音计数
if (volume <= MUTE_VOLUME) {
mEndMuteCount++
} else {
mEndMuteCount = 0
}
//如果达到静音最大次数停止录音
if (mEndMuteCount >= mEndMuteMaxCount) {
closeVad()
return true
}
}
return false
}
return false
}
private fun closeVad() {
mConfig = null
mCount = 0
mBeginMuteCount = 0
mBeginMuteMaxCount = 9
mEndMuteCount = 0
mEndMuteMaxCount = 9
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。