Skip to content

Commit 27962be

Browse files
committed
fix calculateAmplitude by @itsmeinteger
1 parent 27cfd99 commit 27962be

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

encoder/src/main/java/com/pedro/encoder/input/audio/AudioUtils.kt

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.pedro.encoder.input.audio
22

3+
import kotlin.math.abs
4+
35
class AudioUtils {
46

57
fun applyVolumeAndMix(
@@ -32,15 +34,16 @@ class AudioUtils {
3234
}
3335

3436
/**
35-
* assume always pcm 16bit
37+
* Calculate amplitude peaks. Assume always pcm 16bit
3638
* @return value from 0f to 100f
3739
*/
3840
fun calculateAmplitude(buffer: ByteArray): Float {
3941
if (buffer.size % 2 != 0) return 0f //invalid buffer
4042
var amplitude = 0
4143
for (i in buffer.indices step 2) {
42-
val sample = ((buffer[i + 1].toInt() shl 8) or (buffer[i].toInt() and 0xFF))
43-
if (sample > amplitude) amplitude = sample
44+
val sample = ((buffer[i + 1].toInt() shl 8) or (buffer[i].toInt() and 0xFF)).toShort().toInt()
45+
val sampleAmplitude = abs(sample)
46+
if (sampleAmplitude > amplitude) amplitude = sampleAmplitude
4447
}
4548
return (amplitude / Short.MAX_VALUE.toFloat()) * 100
4649
}

0 commit comments

Comments
 (0)