I found this android code to record the user sound when he/she starts to speak and stop recording when he/she stops. But the problem is that the recording stops very quickly
Code from this post is working. But has some issue. The fact is that the record is interrupting too severely abruptly. And sound is playing by stuttering. For solving I created conter silenceDegree.
See my Kotlin code:
var threshold: Short = 5000
val SILENCE_DEGREE = 15
//buffer size - need be fixed, established value for IOS compatibility
val buffer = ShortArray(MIN_SIZE)
var silenceDegree = 0
while (record) {
val bytesRead = audioRecord?.read(buffer, 0, MIN_SIZE)
if (bytesRead != null) {
if (bytesRead > 0) {
val foundPeak = searchThreshold(buffer, threshold)
if (foundPeak == -1) {
if (silenceDegree <= SILENCE_DEGREE) {
silenceDegree++
}
} else {
silenceDegree = 0
}
//stoping to send, only when counter became equals SILENCE_DEGREE
if (silenceDegree < SILENCE_DEGREE) {
//SEND USEFUL DATA
handler.sendDataOnRecord(INSTANCE.shorts2Bytes(buffer))
}
} else {
if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) {
// This can happen if there is already an active
// AudioRecord (e.g. in another tab).
record = false;
}
}
}
}