Normalize audio before recording (#1213)

#1213 Normalize audio before recording
This commit is contained in:
Doug Hoffman
2022-05-01 05:57:32 -04:00
committed by GitHub
parent adcb55ffbc
commit 8148ca48af
2 changed files with 44 additions and 0 deletions

View File

@@ -24,7 +24,10 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.Float;
import java.lang.Math;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class AudioUtils
@@ -78,4 +81,43 @@ public class AudioUtils
return stream.toByteArray();
}
/**
* Normalize audio samples
*/
public static List<float[]> normalize(List<float[]> audioBuffers)
{
float targetMax = 0.95f; // -0.44dBFS
float max = 0.1f; // Initialize at 0.1 (-20dBFS) to limit maximum gain
for(float[] audioBuffer: audioBuffers)
{
for(float value: audioBuffer)
{
float newMax = Math.max(max, Math.abs(value));
if(!Float.isNaN(newMax))
{
max = newMax;
}
}
}
if(targetMax == max)
{
return audioBuffers;
}
float gain = targetMax / max;
for(float[] audioBuffer: audioBuffers)
{
for(int i=0;i<audioBuffer.length;i++)
{
audioBuffer[i] *= gain;
}
}
return audioBuffers;
}
}

View File

@@ -18,6 +18,7 @@
*/
package io.github.dsheirer.audio.convert;
import io.github.dsheirer.audio.AudioUtils;
import io.github.dsheirer.dsp.filter.resample.RealResampler;
import io.github.dsheirer.sample.ConversionUtils;
import net.sourceforge.lame.lowlevel.LameEncoder;
@@ -73,6 +74,7 @@ public class MP3AudioConverter implements IAudioConverter
public List<byte[]> convert(List<float[]> audioPackets)
{
List<byte[]> converted = new ArrayList<>();
audioPackets = AudioUtils.normalize(audioPackets);
if(mResampler != null)
{