Note
Go to the end to download the full example code.
Compressor and limiter
A compressor reduces the level above a threshold and a limiter holds the peak under a ceiling. Both are in-place methods, so the examples work on copies.
import numpy as np
import audio_samples as aus
from audio_samples import mpl
A quiet tone, then the same tone 14 dB louder.
compressed = audio.copy()
config = aus.CompressorConfig.vocal
print(f"threshold {config.threshold_db} dB, ratio {config.ratio}, makeup {config.makeup_gain_db} dB")
compressed.apply_compressor(config)
limited = audio.copy()
ceiling = aus.LimiterConfig.mastering()
print(f"ceiling {ceiling.ceiling_db} dB")
limited.apply_limiter(ceiling)
print(f"peak: original {audio.peak():.3f}, compressed {compressed.peak():.3f}, limited {limited.peak():.3f}")
loud = compressed.to_numpy()[sr + sr // 2 :]
quiet = compressed.to_numpy()[sr // 2 : sr]
assert loud.max() / quiet.max() < 5.0 # the input steps up 5 times (14 dB)
assert limited.peak() <= 10 ** (ceiling.ceiling_db / 20) * 1.01
fig, axes = mpl.plot_waveform_comparison(
[audio, compressed, limited], ["Original", "Compressor", "Limiter"], title="Dynamics"
)

threshold -18.0 dB, ratio 3.0, makeup 3.0 dB
ceiling -0.3 dB
peak: original 0.500, compressed 0.706, limited 0.500
Total running time of the script: (0 minutes 0.236 seconds)