soundmentations.PadToLength

class soundmentations.PadToLength(pad_length: int, p: float = 1.0)[source]

Bases: BasePad

Pad or trim audio to exact target length using end operations.

  • If shorter: adds zeros at the end to reach exact length

  • If longer: trims from the end to reach exact length

  • If equal: returns unchanged

Parameters:
  • pad_length (int) – Exact target length for the audio in samples.

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

Examples

Normalize all audio to exact length:

>>> import numpy as np
>>> from soundmentations.transforms.time import PadToLength
>>>
>>> # Short audio
>>> short_audio = np.array([1, 2, 3])
>>> # Long audio
>>> long_audio = np.arange(10)
>>>
>>> pad_transform = PadToLength(pad_length=5)
>>>
>>> result1 = pad_transform(short_audio)
>>> print(result1)  # [1 2 3 0 0]
>>>
>>> result2 = pad_transform(long_audio)
>>> print(result2)  # [0 1 2 3 4]

Use for fixed-length model inputs:

>>> # Ensure all audio is exactly 2 seconds for ML model
>>> normalize_length = PadToLength(pad_length=88200)  # 2s at 44.1kHz
>>> model_input = normalize_length(variable_length_audio)