Android audio capture silence detection

前端 未结 4 921
-上瘾入骨i
-上瘾入骨i 2020-12-07 23:56

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

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 00:13

    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;
                }
            }
        }
    }
    

提交回复
热议问题