### Install Audiomentations Source: https://github.com/iver56/audiomentations/blob/main/README.md Install the library using pip. This command is compatible with Linux, macOS, and Windows. ```bash pip install audiomentations ``` -------------------------------- ### Install Audiomentations Source: https://context7.com/iver56/audiomentations/llms.txt Install the audiomentations library using pip. Install optional extras for additional transforms. ```bash pip install audiomentations # Install optional extras (Limiter, LoudnessNormalization, Mp3Compression, RoomSimulator) pip install audiomentations[extras] ``` -------------------------------- ### Limiter Usage Examples Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/limiter.md Examples demonstrating how to use the Limiter transform with different threshold modes. ```APIDOC ## Limiter Transform Examples ### Threshold relative to signal peak ```python from audiomentations import Limiter transform = Limiter( min_threshold_db=-16.0, max_threshold_db=-6.0, threshold_mode="relative_to_signal_peak", p=1.0, ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` ### Absolute threshold ```python from audiomentations import Limiter transform = Limiter( min_threshold_db=-16.0, max_threshold_db=-6.0, threshold_mode="absolute", p=1.0, ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` ## Limiter API Parameters - **min_threshold_db** (float): Minimum threshold in Decibel. Default: -24.0. - **max_threshold_db** (float): Maximum threshold in Decibel. Default: -2.0. - **min_attack** (float): Minimum attack time in seconds. Default: 0.0005. - **max_attack** (float): Maximum attack time in seconds. Default: 0.025. - **min_release** (float): Minimum release time in seconds. Default: 0.05. - **max_release** (float): Maximum release time in seconds. Default: 0.7. - **threshold_mode** (str): Specifies the mode for determining the threshold. Choices: `"relative_to_signal_peak"`, `"absolute"`. Default: `"relative_to_signal_peak"`. - **p** (float): The probability of applying this transform. Range: [0.0, 1.0]. Default: 0.5. ``` -------------------------------- ### Usage Example Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/pitch_shift.md Demonstrates how to instantiate and use the PitchShift augmentation with a waveform and sample rate. ```APIDOC ```python from audiomentations import PitchShift transform = PitchShift( min_semitones=-5.0, max_semitones=5.0, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=44100) ``` ``` -------------------------------- ### Usage Example Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/air_absorption.md Demonstrates how to instantiate and use the AirAbsorption transform with custom parameters. ```APIDOC ```python from audiomentations import AirAbsorption transform = AirAbsorption( min_distance=10.0, max_distance=50.0, p=1.0, ) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` ``` -------------------------------- ### Build Distribution Files Source: https://github.com/iver56/audiomentations/blob/main/packaging.md Run these commands to create source distribution (sdist) and wheel binary distribution files. Ensure you have setuptools and wheel installed. ```bash python setup.py sdist bdist_wheel ``` -------------------------------- ### TanhDistortion Usage Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/tanh_distortion.md Example of how to instantiate and use the TanhDistortion transform with custom parameters. ```APIDOC ## TanhDistortion API This section details the parameters available for the `TanhDistortion` transform. ### Parameters * **min_distortion** (`float`): Range: [0.0, 1.0]. Default: `0.01`. Minimum "amount" of distortion to apply to the signal. * **max_distortion** (`float`): Range: [0.0, 1.0]. Default: `0.7`. Maximum "amount" of distortion to apply to the signal. * **p** (`float`): Range: [0.0, 1.0]. Default: `0.5`. The probability of applying this transform. ### Usage Example ```python from audiomentations import TanhDistortion transform = TanhDistortion( min_distortion=0.01, max_distortion=0.7, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` ``` -------------------------------- ### Basic Reverse Augmentation Usage Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/reverse.md This example demonstrates how to apply the Reverse augmentation to an audio waveform with a probability of 1.0. ```python from audiomentations import Reverse transform = Reverse(p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=44100) ``` -------------------------------- ### Upload to PyPI Source: https://github.com/iver56/audiomentations/blob/main/packaging.md Use twine to upload the distribution files to the Python Package Index. Make sure you have twine installed and are authenticated with PyPI. ```bash python -m twine upload dist/* ``` -------------------------------- ### PitchShift Usage Example Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/pitch_shift.md Instantiate and apply the PitchShift transform to an audio waveform. Ensure the waveform and sample rate are provided. ```python from audiomentations import PitchShift transform = PitchShift( min_semitones=-5.0, max_semitones=5.0, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=44100) ``` -------------------------------- ### BandPassFilter Usage Example Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/band_pass_filter.md Instantiate and apply the BandPassFilter to an audio waveform. Ensure the input is a NumPy array and the sample rate is provided. ```python from audiomentations import BandPassFilter transform = BandPassFilter(min_center_freq=100.0, max_center_freq=6000, p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` -------------------------------- ### Apply Post Gain to Match Input Loudness Source: https://context7.com/iver56/audiomentations/llms.txt Wraps another transform and applies a compensating gain after it runs to match the output loudness (RMS, LUFS, or peak) to the input loudness. This example applies PitchShift and then adjusts gain. ```python from audiomentations import PostGain, PitchShift import numpy as np transform = PostGain( transform=PitchShift(min_semitones=-4, max_semitones=4, p=1.0), method="same_rms", # "same_rms", "same_lufs", "peak_normalize_always", # or "peak_normalize_if_too_loud" ) samples = np.random.uniform(-0.2, 0.2, size=(44100,)).astype(np.float32) augmented = transform(samples=samples, sample_rate=44100) # PitchShift applied, then output gained so RMS matches input RMS ``` -------------------------------- ### Aliasing Transform Usage Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/aliasing.md Example of how to use the Aliasing transform with specified sample rate ranges and probability. ```APIDOC ## Aliasing Transform ### Description Downsample the audio to a lower sample rate by linear interpolation, without low-pass filtering it first, resulting in aliasing artifacts. After the downsampling, the signal gets upsampled to the original sample rate again, so the length of the output becomes the same as the length of the input. ### Parameters #### Initialization Parameters - **min_sample_rate** (int) - Required - Minimum target sample rate to downsample to. Unit: Hz. Range: [2, ∞). - **max_sample_rate** (int) - Required - Maximum target sample rate to downsample to. Unit: Hz. Range: [2, ∞). - **p** (float) - Optional - Default: `0.5`. The probability of applying this transform. Range: [0.0, 1.0]. ### Usage Example ```python from audiomentations import Aliasing transform = Aliasing(min_sample_rate=8000, max_sample_rate=30000, p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=44100) ``` ``` -------------------------------- ### Compose Audio Augmentations Source: https://github.com/iver56/audiomentations/blob/main/docs/index.md Use Compose to apply a sequence of audio transforms. This example demonstrates combining Gaussian noise, time stretching, pitch shifting, and sample shifting. Ensure input samples are float32 between -1 and 1. ```python from audiomentations import Compose, AddGaussianNoise, TimeStretch, PitchShift, Shift import numpy as np augment = Compose([ AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.5), TimeStretch(min_rate=0.8, max_rate=1.25, p=0.5), PitchShift(min_semitones=-4, max_semitones=4, p=0.5), Shift(p=0.5), ]) # Generate 2 seconds of dummy audio for the sake of example samples = np.random.uniform(low=-0.2, high=0.2, size=(32000,)).astype(np.float32) # Augment/transform/perturb the audio data augmented_samples = augment(samples=samples, sample_rate=16000) ``` -------------------------------- ### Load Audio with Librosa and Soundfile Source: https://github.com/iver56/audiomentations/blob/main/docs/guides/multichannel_audio_array_shapes.md Demonstrates loading audio files using librosa (mono and multichannel) and soundfile. Note the different output shapes for stereo audio. ```python import librosa import soundfile as sf # Librosa, mono y, sr = librosa.load("stereo_audio_example.wav", sr=None, mono=True) print(y.shape) # (117833,) # Librosa, multichannel y, sr = librosa.load("stereo_audio_example.wav", sr=None, mono=False) print(y.shape) # (2, 117833) # Soundfile y, sr = sf.read("stereo_audio_example.wav") print(y.shape) # (117833, 2) ``` -------------------------------- ### Initialize Mp3Compression Transform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/mp3_compression.md Instantiate the Mp3Compression transform with specified bitrate range, backend, and probability. The 'fast-mp3-augment' backend is recommended for performance. Ensure the sample rate is supported by the chosen backend. ```python from audiomentations import Mp3Compression transform = Mp3Compression( min_bitrate=16, max_bitrate=96, backend="fast-mp3-augment", preserve_delay=False, p=1.0 ) ``` -------------------------------- ### AddGaussianSNR Usage Example Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/add_gaussian_snr.md Instantiate AddGaussianSNR with desired SNR range and probability, then apply it to a waveform. ```python from audiomentations import AddGaussianSNR transform = AddGaussianSNR( min_snr_db=5.0, max_snr_db=40.0, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### Initialize and Apply TimeStretch Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/time_stretch.md Instantiate TimeStretch with desired parameters for rate limits and length preservation, then apply it to an audio waveform. ```python from audiomentations import TimeStretch transform = TimeStretch( min_rate=0.8, max_rate=1.25, leave_length_unchanged=True, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### RoomSimulator: Simulate Parametric Room Acoustics Source: https://context7.com/iver56/audiomentations/llms.txt Synthesizes a room impulse response procedurally and convolves it with audio. Allows fine-grained control over room dimensions, absorption, and positions. The output length may differ from the input. Ensure `numpy` is imported. ```python from audiomentations import RoomSimulator import numpy as np transform = RoomSimulator( min_size_x=3.6, max_size_x=5.6, min_size_y=3.6, max_size_y=3.9, min_size_z=2.4, max_size_z=3.0, min_absorption_value=0.075, max_absorption_value=0.4, calculation_mode="rt60", # or "absorption" min_target_rt60=0.15, # recording studio ~0.3 s, concert hall ~1.5 s max_target_rt60=0.8, use_ray_tracing=True, max_order=3, leave_length_unchanged=False, p=1.0, ) samples = np.random.uniform(-0.2, 0.2, size=(16000,)).astype(np.float32) augmented = transform(samples=samples, sample_rate=16000) # Reverb tail added; output may be longer than input ``` -------------------------------- ### RoomSimulator Parameters Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/room_simulator.md This section details the configurable parameters for the RoomSimulator, including room dimensions, microphone settings, reverberation modes, and simulation options. ```APIDOC ## RoomSimulator API This API allows for the simulation of acoustic environments. Below are the configurable parameters: ### Parameters - **`max_mic_elevation`** (`float`): Maximum elevation of the microphone relative to the source, in radians. Default: `math.pi`. - **`calculation_mode`** (`str`): Determines how the room's acoustic properties are calculated. Choices: `"rt60"`, `"absorption"`. Default: `"absorption"`. - If `"absorption"`, room surfaces are based on `min_absorption_value` and `max_absorption_value`. - If `"rt60"`, surface materials are assigned to achieve target RT60 values specified by `min_target_rt60` and `max_target_rt60`. - **`use_ray_tracing`** (`bool`): Whether to use ray tracing for simulation. Default: `True`. Disabling this improves speed at the cost of accuracy. - **`max_order`** (`int`): Maximum order of reflections for the Image Source Model. Default: `1`. Higher values add more diffuse reverberation but can slow down the process, especially when `calculation_mode="rt60"`. Recommended values for `"rt60"` are around `3-4`. - **`leave_length_unchanged`** (`bool`): If `True`, the output audio length will be equal to the input audio length by chopping off the tail. Default: `False`. - **`padding`** (`float`): Minimum distance in meters between sources/microphones and room walls, floor, or ceiling. Default: `0.1`. - **`p`** (`float`): The probability of applying this transform. Range: `[0.0, 1.0]`. Default: `0.5`. - **`ray_tracing_options`** (`Optional[Dict]`): Options for the ray tracer. See `set_ray_tracing` in the pyroomacoustics library for details. Default: `None`. ``` -------------------------------- ### Trim Silence with Default Parameters Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/trim.md Apply the Trim transform to remove silence from the start and end of an audio waveform. Uses the default top_db parameter value. ```python from audiomentations import Trim transform = Trim( top_db=30.0, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### Inspect and Freeze Transform Parameters Source: https://context7.com/iver56/audiomentations/llms.txt Demonstrates how to inspect the parameters of a transform after it has been called and how to freeze these parameters to apply the exact same augmentation to multiple signals. ```python from audiomentations import Gain import numpy as np augment = Gain(p=1.0) signal = np.random.uniform(-0.2, 0.2, size=(32000,)).astype(np.float32) target = np.random.uniform(-0.2, 0.2, size=(32000,)).astype(np.float32) augmented_signal = augment(samples=signal, sample_rate=16000) print(augment.parameters) # {'should_apply': True, 'amplitude_ratio': 0.9688148624484364} augment.freeze_parameters() # lock parameters at current values augmented_target = augment(samples=target, sample_rate=16000) print(augment.parameters) # {'should_apply': True, 'amplitude_ratio': 0.9688148624484364} (identical) augment.unfreeze_parameters() # allow new random parameters next call ``` -------------------------------- ### Add Background Noise with Absolute RMS Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/add_background_noise.md Use this when you want to control the absolute loudness of the background noise, irrespective of the input signal's level. Includes an example of applying a noise transform. ```python from audiomentations import AddBackgroundNoise, PolarityInversion transform = AddBackgroundNoise( sounds_path="/path/to/folder_with_sound_files", noise_rms="absolute", min_absolute_rms_db=-45.0, max_absolute_rms_db=-15.0, noise_transform=PolarityInversion(), p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### Add Background Noise with Relative RMS Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/add_background_noise.md Use this when you want the noise level to be relative to the input signal's level. If the input is silent, no noise will be added. Includes an example of applying a noise transform. ```python from audiomentations import AddBackgroundNoise, PolarityInversion transform = AddBackgroundNoise( sounds_path="/path/to/folder_with_sound_files", min_snr_db=3.0, max_snr_db=30.0, noise_transform=PolarityInversion(), p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### RoomSimulator Source: https://context7.com/iver56/audiomentations/llms.txt Synthesizes a room impulse response procedurally and convolves it with the audio. ```APIDOC ## RoomSimulator ### Description Synthesizes a room impulse response procedurally using `pyroomacoustics` and convolves it with the audio. Allows fine-grained control over room dimensions, absorption coefficients, source and microphone positions. ### Parameters - `min_size_x`, `max_size_x` (float) - Minimum and maximum size of the room along the X-axis. - `min_size_y`, `max_size_y` (float) - Minimum and maximum size of the room along the Y-axis. - `min_size_z`, `max_size_z` (float) - Minimum and maximum size of the room along the Z-axis. - `min_absorption_value`, `max_absorption_value` (float) - Minimum and maximum absorption values for the room surfaces. - `calculation_mode` (str) - Mode for calculation ('rt60' or 'absorption'). - `min_target_rt60`, `max_target_rt60` (float) - Minimum and maximum target reverberation times (RT60). - `use_ray_tracing` (bool) - Whether to use ray tracing for simulation. - `max_order` (int) - Maximum order for the simulation. - `leave_length_unchanged` (bool) - If True, the reverb tail is not added, preserving input length. - `p` (float) - Probability of applying the transform. ``` -------------------------------- ### OneOf Transform Selection Source: https://github.com/iver56/audiomentations/blob/main/docs/index.md Use OneOf to randomly select and apply one transform from a list. Weights can be provided to influence the probability of selection for each transform. This example uses different pitch shifting methods. ```python from audiomentations import OneOf, PitchShift pitch_shift = OneOf( transforms=[ PitchShift(method="librosa_phase_vocoder"), PitchShift(method="signalsmith_stretch"), ], p=1.0, weights=[0.1, 0.9], ) ``` -------------------------------- ### Padding Augmentation Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/padding.md This augmentation applies padding to the audio signal. You can control the mode of padding, the minimum and maximum fraction of the signal to pad, and which section (start or end) to pad. The probability of applying the transform can also be set. ```APIDOC ## Padding Augmentation Applies padding to the audio signal by taking a fraction of the start or end and replacing that portion with padding. This can be useful for training ML models on padded inputs. ### Parameters - **mode** (str) - Optional - Default: "silence". Choices: "silence", "wrap", "reflect". Padding mode. - **min_fraction** (float) - Optional - Default: 0.01. Minimum fraction of the signal duration to be padded. Range: [0.0, 1.0]. - **max_fraction** (float) - Optional - Default: 0.7. Maximum fraction of the signal duration to be padded. Range: [0.0, 1.0]. - **pad_section** (str) - Optional - Default: "end". Choices: "start", "end". Which part of the signal should be replaced with padding. - **p** (float) - Optional - Default: 0.5. The probability of applying this transform. Range: [0.0, 1.0]. ``` -------------------------------- ### PostGain Transform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/post_gain.md The PostGain transform can be initialized with a callable transform and a method for gain adjustment. The available methods are 'same_rms', 'same_lufs', 'peak_normalize_always', and 'peak_normalize_if_too_loud'. ```APIDOC ## PostGain ### Description Gain up or down the audio after the given transform (or set of transforms) has processed the audio. There are several methods that determine how the audio should be gained. `PostGain` can be useful for compensating for any gain differences introduced by a (set of) transform(s), or for preventing clipping in the output. ### Parameters - **`transform`** (`Callable[[NDArray[np.float32], int], NDArray[np.float32]]`) - Required - A callable to be applied. It should input samples (ndarray), sample_rate (int) and optionally some user-defined keyword arguments. - **`method`** (`str`) - Required - This parameter defines the method for choosing the post gain amount. Choices include: `"same_rms"`, `"same_lufs"`, `"peak_normalize_always"`, or `"peak_normalize_if_too_loud"`. ### Method Details - **`"same_rms"`**: The sound gets post-gained so that the RMS (Root Mean Square) of the output matches the RMS of the input. - **`"same_lufs"`**: The sound gets post-gained so that the LUFS (Loudness Units Full Scale) of the output matches the LUFS of the input. - **`"peak_normalize_always"`**: The sound gets peak normalized (gained up or down so that the absolute value of the most extreme sample in the output is 1.0). - **`"peak_normalize_if_too_loud"`**: The sound gets peak normalized if it is too loud (max absolute value greater than 1.0). This option can be useful for avoiding clipping. ``` -------------------------------- ### BandPassFilter Initialization and Usage Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/band_pass_filter.md This snippet shows how to initialize the BandPassFilter with custom parameters and apply it to an audio waveform. ```APIDOC ## BandPassFilter Apply band-pass filtering to the input audio. Filter steepness (6/12/18... dB / octave) is parametrized. Can also be set for zero-phase filtering (will result in a 6 dB drop at cutoffs). ### Parameters - **min_center_freq** (float): Minimum center frequency in hertz. Default: `200.0`. - **max_center_freq** (float): Maximum center frequency in hertz. Default: `4000.0`. - **min_bandwidth_fraction** (float): Minimum bandwidth relative to center frequency. Range: [0.0, 2.0]. Default: `0.5`. - **max_bandwidth_fraction** (float): Maximum bandwidth relative to center frequency. Range: [0.0, 2.0]. Default: `1.99`. - **min_rolloff** (int): Minimum filter roll-off (in dB/octave). Must be a multiple of 6 (or 12 if `zero_phase` is `True`). Default: `12`. - **max_rolloff** (int): Maximum filter roll-off (in dB/octave). Must be a multiple of 6 (or 12 if `zero_phase` is `True`). Default: `24`. - **zero_phase** (bool): Whether filtering should be zero phase. Default: `False`. - **p** (float): The probability of applying this transform. Range: [0.0, 1.0]. Default: `0.5`. ### Usage Example ```python from audiomentations import BandPassFilter transform = BandPassFilter(min_center_freq=100.0, max_center_freq=6000, p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` ``` -------------------------------- ### Apply Custom Callable with Lambda Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/lambda.md Use the Lambda transform to apply a custom Python function to audio samples. The callable should accept samples and sample rate, and can optionally take additional keyword arguments. This example demonstrates integrating a custom gain adjustment for the left channel within a `OneOf` composition. ```python import random from audiomentations import Lambda, OneOf, Gain def gain_only_left_channel(samples, sample_rate): samples[0, :] *= random.uniform(0.8, 1.25) return samples transform = OneOf( transforms=[Lambda(transform=gain_only_left_channel, p=1.0), Gain(p=1.0)] ) augmented_sound = transform(my_stereo_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### AdjustDuration: Trim or Pad to Fixed Length Source: https://context7.com/iver56/audiomentations/llms.txt Trims or pads audio to a target duration, specified in samples or seconds. Useful for batching variable-length audio. The `padding_mode` can be "silence", "wrap", or "reflect", and `padding_position` can be "start" or "end". Ensure `numpy` is imported. ```python from audiomentations import AdjustDuration import numpy as np # Target specified in samples transform_samples = AdjustDuration(duration_samples=24000, p=1.0) # Target specified in seconds transform_seconds = AdjustDuration( duration_seconds=3.0, padding_mode="silence", # "silence", "wrap", or "reflect" padding_position="end", # "start" or "end" p=1.0, ) samples = np.random.uniform(-0.2, 0.2, size=(40000,)).astype(np.float32) augmented = transform_samples(samples=samples, sample_rate=16000) assert augmented.shape == (24000,) # exactly 1.5 s at 16 kHz ``` -------------------------------- ### Convert Channels-Last to Channels-First with NumPy Source: https://github.com/iver56/audiomentations/blob/main/docs/guides/multichannel_audio_array_shapes.md Shows how to convert audio data from the channels-last format (samples, channels) to the channels-first format (channels, samples) using NumPy's transpose operation. ```python import numpy as np # Assuming y is your audio data in channels-last format y_transposed = np.transpose(y) # Alternative, shorter syntax: y_transposed = y.T ``` -------------------------------- ### Apply BitCrush Transform in Python Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/bit_crush.md Instantiate the BitCrush transform with specified minimum and maximum bit depths and apply it to an audio waveform. Set p=1.0 to ensure the transform is always applied. ```python from audiomentations import BitCrush transform = BitCrush(min_bit_depth=5, max_bit_depth=14, p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` -------------------------------- ### Apply Impulse Response Transform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/apply_impulse_response.md Instantiate the ApplyImpulseResponse transform and apply it to a waveform. Ensure the ir_path points to a folder containing impulse response audio files. Set p=1.0 to guarantee application. ```python from audiomentations import ApplyImpulseResponse transform = ApplyImpulseResponse(ir_path="/path/to/sound_folder", p=1.0) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` -------------------------------- ### Apply Mp3Compression to Waveform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/mp3_compression.md Apply the initialized Mp3Compression transform to a waveform numpy array. The sample rate must be provided and should be one of the supported rates for the selected backend. ```python augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` -------------------------------- ### Initialize and Apply AirAbsorption Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/air_absorption.md Instantiate the AirAbsorption transform with specified distance ranges and apply it to a waveform. Ensure the sample rate is appropriate for high-frequency content. ```python from audiomentations import AirAbsorption transform = AirAbsorption( min_distance=10.0, max_distance=50.0, p=1.0, ) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` -------------------------------- ### Ensure C-Contiguous Array for Audio Processing Source: https://github.com/iver56/audiomentations/blob/main/docs/guides/multichannel_audio_array_shapes.md Explains the importance of C-contiguous memory layout for some audio processing libraries and demonstrates how to ensure it using `np.ascontiguousarray` after transposing. ```python y_transposed_contiguous = np.ascontiguousarray(y_transposed) ``` -------------------------------- ### Inspect Parameters in Compose Pipeline Source: https://context7.com/iver56/audiomentations/llms.txt Shows how to iterate through transforms within a Compose pipeline and inspect the parameters of each individual transform after augmentation. ```python from audiomentations import Compose, AddGaussianNoise, TimeStretch, PitchShift, Shift import numpy as np augment = Compose([ AddGaussianNoise(p=0.5), TimeStretch(p=0.5), PitchShift(p=0.5), Shift(p=0.5), ]) samples = np.random.uniform(-0.2, 0.2, size=(32000,)).astype(np.float32) augmented = augment(samples=samples, sample_rate=16000) for t in augment.transforms: print(f"{t.__class__.__name__}: {t.parameters}") # AddGaussianNoise: {'should_apply': True, 'amplitude': 0.0027} # TimeStretch: {'should_apply': True, 'rate': 1.158} # PitchShift: {'should_apply': False} # Shift: {'should_apply': False} ``` -------------------------------- ### Source and Microphone Placement Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/room_simulator.md Defines the ranges for placing sound sources and microphones within the simulated room. ```APIDOC ## Source and Microphone Placement ### Parameters - **min_source_x** (float) - Optional - Minimum x location of the source in meters. Default: `0.1`. - **max_source_x** (float) - Optional - Maximum x location of the source in meters. Default: `3.5`. - **min_source_y** (float) - Optional - Minimum y location of the source in meters. Default: `0.1`. - **max_source_y** (float) - Optional - Maximum y location of the source in meters. Default: `2.7`. - **min_source_z** (float) - Optional - Minimum z location of the source in meters. Default: `1.0`. - **max_source_z** (float) - Optional - Maximum z location of the source in meters. Default: `2.1`. - **min_mic_distance** (float) - Optional - Minimum distance of the microphone from the source in meters. Default: `0.15`. - **max_mic_distance** (float) - Optional - Maximum distance of the microphone from the source in meters. Default: `0.35`. - **min_mic_azimuth** (float) - Optional - Minimum azimuth (angle around z axis) of the microphone relative to the source in radians. Default: `-math.pi`. - **max_mic_azimuth** (float) - Optional - Maximum azimuth (angle around z axis) of the microphone relative to the source in radians. Default: `math.pi`. - **min_mic_elevation** (float) - Optional - Minimum elevation of the microphone relative to the source in radians. Default: `-math.pi`. ``` -------------------------------- ### SevenBandParametricEQ Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/seven_band_parametric_eq.md Initializes the SevenBandParametricEQ transform with configurable parameters for gain, Q values, and center frequencies. ```APIDOC ## SevenBandParametricEQ() ### Description Initializes the SevenBandParametricEQ transform, which applies a 7-band parametric equalizer to audio signals. This transform can adjust the volume of different frequency bands by applying randomized gains, Q values, and center frequencies. ### Parameters #### Keyword Arguments - **min_gain_db** (float) - Optional - Default: -12.0. The minimum number of dB to cut or boost a band. - **max_gain_db** (float) - Optional - Default: 12.0. The maximum number of dB to cut or boost a band. - **p** (float) - Optional - Default: 0.5. The probability of applying this transform. Must be in the range [0.0, 1.0]. ``` -------------------------------- ### BandStopFilter Parameters Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/band_stop_filter.md Configuration options for the BandStopFilter augmentation. ```APIDOC ## BandStopFilter API ### Parameters - **min_center_freq** (float, optional): Minimum center frequency in hertz. Default: `200.0`. - **max_center_freq** (float, optional): Maximum center frequency in hertz. Default: `4000.0`. - **min_bandwidth_fraction** (float, optional): Minimum bandwidth fraction relative to center frequency. Default: `0.5`. - **max_bandwidth_fraction** (float, optional): Maximum bandwidth fraction relative to center frequency. Default: `1.99`. - **min_rolloff** (int, optional): Minimum filter roll-off in dB/octave. Must be a multiple of 6 (or 12 if `zero_phase` is `True`). Default: `12`. - **max_rolloff** (int, optional): Maximum filter roll-off in dB/octave. Must be a multiple of 6 (or 12 if `zero_phase` is `True`). Default: `24`. - **zero_phase** (bool, optional): Whether filtering should be zero phase. If `True`, it does not affect the phase but sounds 3 dB lower at the cutoff frequency compared to the non-zero phase case (6 dB vs. 3 dB). It is also twice as slow. Default: `False`. - **p** (float, optional): The probability of applying this transform. Range: [0.0, 1.0]. Default: `0.5`. ``` -------------------------------- ### Freezing and Reusing Transform Parameters Source: https://github.com/iver56/audiomentations/blob/main/docs/guides/transform_parameters.md To apply the exact same transformation to multiple audio inputs, call `.freeze_parameters()` after the first application. This preserves the chosen parameters. Call `.unfreeze_parameters()` to resume random parameter selection. ```python from audiomentations import Gain import numpy as np augment = Gain(p=1.0) samples = np.random.uniform(low=-0.2, high=0.2, size=(32000,)).astype(np.float32) samples2 = np.random.uniform(low=-0.2, high=0.2, size=(32000,)).astype(np.float32) augmented_samples = augment(samples=samples, sample_rate=16000) augment.freeze_parameters() print(augment.parameters) augmented_samples2 = augment(samples=samples2, sample_rate=16000) print(augment.parameters) augment.unfreeze_parameters() ``` -------------------------------- ### Trim Transform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/trim.md This snippet demonstrates how to apply the Trim transform to an audio waveform. It initializes the transform with a specific `top_db` value and probability `p`, then applies it to a NumPy array representing the waveform. ```APIDOC ## Trim Transform ### Description Applies the Trim transformation to an audio waveform to remove leading and trailing silence. ### Parameters #### `top_db` (float) - Required: No - Default: `30.0` - Description: The threshold in Decibels below which audio is considered silence and will be trimmed. A lower value means more silence will be trimmed. #### `p` (float) - Required: No - Default: `0.5` - Range: [0.0, 1.0] - Description: The probability of applying this transform. ### Usage Example ```python from audiomentations import Trim transform = Trim( top_db=30.0, p=1.0 ) augmented_sound = transform(samples=my_waveform_ndarray, sample_rate=16000) ``` ### Input-Output Example This example shows the effect of the Trim transform on an audio signal, visualizing the input and transformed waveforms and spectrograms, along with playable audio controls. ``` -------------------------------- ### Mp3Compression API Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/mp3_compression.md Configuration options for the Mp3Compression transform. ```APIDOC ## Mp3Compression Compress the audio using an MP3 encoder to lower the audio quality. This may help machine learning models deal with compressed, low-quality audio. ### Parameters * **`min_bitrate`** (int): Minimum bitrate in kbps. Range: [8, `max_bitrate`]. Default: `8`. * **`max_bitrate`** (int): Maximum bitrate in kbps. Range: [`min_bitrate`, 320]. Default: `64`. * **`backend`** (str): The backend to use for MP3 compression. Choices: `"fast-mp3-augment"`, `"pydub"`, `"lameenc"`. Default: `"fast-mp3-augment"`. * `"fast-mp3-augment"`: In-memory computation with parallel threads. Uses LAME encoder and minimp3 decoder. * `"pydub"`: Uses pydub + ffmpeg. Does not delay output. Slow, writes temporary files. Deprecated. * `"lameenc"`: Writes temporary files. Introduces delay. Deprecated. * **`preserve_delay`** (bool): If `False`, output length and timing match input. If `True`, includes encoder and filter delay, making output longer and delayed. Default: `False`. * **`quality`** (int): LAME-specific parameter controlling quality vs. speed. Range: [0, 9]. Default: `7`. Ignored if `backend="pydub"`. * **`p`** (float): The probability of applying this transform. Range: [0.0, 1.0]. Default: `0.5`. ### Usage Example ```python from audiomentations import Mp3Compression transform = Mp3Compression( min_bitrate=16, max_bitrate=96, backend="fast-mp3-augment", preserve_delay=False, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=48000) ``` ``` -------------------------------- ### TimeStretch Transform Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/time_stretch.md This snippet demonstrates how to instantiate and use the TimeStretch transform. It allows for flexible control over the rate of time stretching, whether the output length should match the input, and the probability of applying the transform. ```APIDOC ## TimeStretch Change the speed or duration of the signal without changing the pitch. ### Parameters * **min_rate** (`float`): Default: `0.8`. Minimum time-stretch rate. Values less than 1.0 slow down the audio. * **max_rate** (`float`): Default: `1.25`. Maximum time-stretch rate. Values greater than 1.0 speed up the audio. * **leave_length_unchanged** (`bool`): Default: `True`. If `True`, the output audio will have the same duration as the input audio. If `False`, the duration will be altered. * **method** (`str`): Default: `"signalsmith_stretch"`. The time stretching algorithm to use. Choices: `"librosa_phase_vocoder"`, `"signalsmith_stretch"`. * **p** (`float`): Default: `0.5`. The probability of applying this transform. ### Usage Example ```python from audiomentations import TimeStretch transform = TimeStretch( min_rate=0.8, max_rate=1.25, leave_length_unchanged=True, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ``` ``` -------------------------------- ### Mp3Compression: Simulate MP3 Lossy Compression Source: https://context7.com/iver56/audiomentations/llms.txt Encodes audio to MP3 at a random bitrate and decodes it back to simulate lossy compression artifacts. The `backend` can be set to "fast-mp3-augment" (recommended) or others. Ensure `numpy` is imported. ```python from audiomentations import Mp3Compression import numpy as np transform = Mp3Compression( min_bitrate=16, max_bitrate=96, backend="fast-mp3-augment", # recommended; in-memory, parallel threads preserve_delay=False, # output aligned with input in time p=1.0, ) samples = np.random.uniform(-0.2, 0.2, size=(48000,)).astype(np.float32) augmented = transform(samples=samples, sample_rate=48000) # Supported sample rates for fast-mp3-augment: 8000, 11025, 12000, 16000, # 22050, 24000, 32000, 44100, 48000 ``` -------------------------------- ### LoudnessNormalization Parameters Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/loudness_normalization.md Configuration options for the LoudnessNormalization transform. ```APIDOC ## LoudnessNormalization Apply a constant amount of gain to match a specific loudness (in LUFS). This is an implementation of ITU-R BS.1770-4. ### Parameters - **min_lufs** (float) - Optional - Minimum loudness target in LUFS. Default: -31.0. - **max_lufs** (float) - Optional - Maximum loudness target in LUFS. Default: -13.0. - **p** (float) - Optional - The probability of applying this transform. Range: [0.0, 1.0]. Default: 0.5. ### Warning This transform can return samples outside the [-1, 1] range, which may lead to clipping or wrap distortion. ``` -------------------------------- ### Apply Tanh Distortion Source: https://github.com/iver56/audiomentations/blob/main/docs/waveform_transforms/tanh_distortion.md Instantiate TanhDistortion with specified min/max distortion and probability, then apply it to a waveform. ```python from audiomentations import TanhDistortion transform = TanhDistortion( min_distortion=0.01, max_distortion=0.7, p=1.0 ) augmented_sound = transform(my_waveform_ndarray, sample_rate=16000) ```