soundmentations.Compressor

class soundmentations.Compressor(threshold: float, ratio: float, attack_time: float, release_time: float, p: float = 1.0)[source]

Bases: BaseCompressor

Apply dynamic range compression to the audio sample.

This compressor uses an envelope follower with configurable attack and release times to track the signal level, then applies gain reduction based on a threshold and compression ratio.

Parameters:
  • threshold (float) – The threshold above which compression is applied, in dB. Typical values range from -40 to -6 dB.

  • ratio (float) – The compression ratio to apply. Must be >= 1.0. - 1.0 = no compression - 2.0 = 2:1 compression - 10.0 = 10:1 compression (heavy compression)

  • attack_time (float) – Attack time in milliseconds. How quickly the compressor responds to signals above the threshold. Typical values: 0.1 to 100 ms.

  • release_time (float) – Release time in milliseconds. How quickly the compressor stops compressing after the signal falls below threshold. Typical values: 10 to 1000 ms.

  • p (float, optional) – Probability of applying the transform, by default 1.0.

Examples

>>> import numpy as np
>>> from soundmentations.transforms.amplitude.compressor import Compressor
>>>
>>> # Create a compressor with 4:1 ratio and -12dB threshold
>>> compressor = Compressor(threshold=-12.0, ratio=4.0,
...                        attack_time=5.0, release_time=50.0)
>>>
>>> # Apply to a sine wave
>>> sample_rate = 44100
>>> duration = 1.0
>>> t = np.linspace(0, duration, int(sample_rate * duration))
>>> audio = np.sin(2 * np.pi * 440 * t) * 0.8  # 440Hz sine wave
>>> compressed = compressor(audio, sample_rate)

Notes

The compressor implementation uses: - Linear threshold conversion from dB - Exponential envelope follower with separate attack/release coefficients - Logarithmic gain calculation for smooth compression curves

The envelope follower uses first-order low-pass filtering to smooth the absolute value of the input signal, with different time constants for attack (signal increasing) and release (signal decreasing).