soundmentations.RandomTrim¶
- class soundmentations.RandomTrim(duration: float | Tuple[float, float], p: float = 1.0)[source]¶
Bases:
BaseTrim
Randomly trim audio by selecting a random segment of specified duration.
This transform randomly selects a continuous segment from the audio, useful for data augmentation where you want random crops of fixed or variable duration.
- Parameters:
Examples
Fixed duration random trimming:
>>> import numpy as np >>> from soundmentations.transforms.time import RandomTrim >>> >>> # Always keep 2 seconds randomly >>> trim_transform = RandomTrim(duration=2.0) >>> trimmed = trim_transform(audio, sample_rate=44100) >>> print(len(trimmed) / 44100) # 2.0 seconds
Variable duration random trimming:
>>> # Keep 1-3 seconds randomly >>> variable_trim = RandomTrim(duration=(1.0, 3.0)) >>> result = variable_trim(audio, sample_rate=44100)
Use for data augmentation:
>>> import soundmentations as S >>> >>> # Random crop and normalize for training >>> augment = S.Compose([ ... S.RandomTrim(duration=(0.5, 2.5), p=0.8), ... S.PadToLength(pad_length=88200, p=1.0), # 2 seconds ... S.Gain(gain=(-6, 6), p=0.5) ... ]) >>> >>> augmented = augment(training_audio, sample_rate=44100)