import argparse
import os
import sys
from typing import Callable, Dict, List
import librosa
import soundfile as sf
from audiomentations import (
Compose,
Gain,
PitchShift,
TimeStretch,
AddGaussianNoise,
FrequencyMask,
LowPassFilter,
HighPassFilter,
BandPassFilter,
Resample,
)
from audiomentations.core.transforms_interface import BaseWaveformTransform
# Supported audio file extensions
AUDIO_EXTENSIONS = [
".mp3",
".wav",
".flac",
".aac",
".ogg",
".m4a",
".wma",
".alac",
".aiff",
".opus",
]
# Mapping of augmentation names to their corresponding functions
AUGMENTATION_MAPPING: Dict[str, Callable[[], BaseWaveformTransform]] = {
"time_stretching": lambda: TimeStretch(min_rate=0.8, max_rate=1.25, p=1.0),
"pitch_shifting": lambda: PitchShift(min_semitones=-4, max_semitones=4, p=1.0),
"noise_injection": lambda: AddGaussianNoise(
min_amplitude=0.001, max_amplitude=0.015, p=1.0
),
"gain_adjustment": lambda: Gain(min_gain_in_db=-12, max_gain_in_db=12, p=1.0),
"frequency_masking": lambda: FrequencyMask(
min_frequency_band=0.0, max_frequency_band=0.5, p=1.0
),
"low_pass_filter": lambda: LowPassFilter(
min_cutoff_freq=1500, max_cutoff_freq=7500, p=1.0
),
"high_pass_filter": lambda: HighPassFilter(
min_cutoff_freq=20, max_cutoff_freq=2400, p=1.0
),
"band_pass_filtering": lambda: BandPassFilter(
min_center_freq=200.0,
max_center_freq=4000.0,
min_bandwidth_fraction=0.5,
max_bandwidth_fraction=1.99,
p=1.0,
),
"resampling": lambda: Resample(
min_sample_rate=int(0.8 * 44100), max_sample_rate=int(1.2 * 44100), p=1.0
),
}
def parse_arguments():
"""
Parse command-line arguments.
Returns:
argparse.Namespace: Parsed command-line arguments.
"""
parser = argparse.ArgumentParser(description="Audio Augmentation Script")
parser.add_argument(
"--input_dir",
type=str,
required=True,
help="Directory containing input audio files.",
)
parser.add_argument(
"--output_dir",
type=str,
required=True,
help="Directory to save augmented audio files.",
)
parser.add_argument(
"--sampling_rate",
type=int,
default=None,
help="Target sampling rate for audio files.",
)
parser.add_argument(
"--mono", action="store_true", help="Convert audio files to mono."
)
parser.add_argument(
"--augmentations", nargs="+", help="List of augmentations to apply."
)
parser.add_argument(
"--list_augmentations",
action="store_true",
help="List available augmentations and exit.",
)
args = parser.parse_args()
return args
def create_augmentation(aug_name: str) -> BaseWaveformTransform:
"""
Create an audio augmentation based on the given augmentation name.
Parameters:
aug_name (str): The name of the augmentation.
Returns:
BaseWaveformTransform: An augmentation object from audiomentations.
Raises:
ValueError: If the augmentation name is not recognized.
"""
aug_name = aug_name.lower()
if aug_name in AUGMENTATION_MAPPING:
return AUGMENTATION_MAPPING[aug_name]()
else:
raise ValueError(f"Augmentation '{aug_name}' not recognized or not implemented.")
def main():
"""
Main function to perform audio augmentation based on user inputs.
"""
args = parse_arguments()
input_dir = args.input_dir
output_dir = args.output_dir
sampling_rate = args.sampling_rate
convert_mono = args.mono
augmentations_list = args.augmentations
# List available augmentations and exit
if args.list_augmentations:
print("Available augmentations:")
for aug in AUGMENTATION_MAPPING.keys():
print(f"- {aug}")
sys.exit(0)
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Get list of audio files with supported extensions
audio_files = [
os.path.join(root, file)
for root, _, files in os.walk(input_dir)
for file in files
if os.path.splitext(file)[1].lower() in AUDIO_EXTENSIONS
]
if not audio_files:
print(f"No audio files found in '{input_dir}'.")
sys.exit(1)
# Create augmentation pipeline
if augmentations_list:
try:
augmentations = [
create_augmentation(aug_name) for aug_name in augmentations_list
]
except ValueError as e:
print(e)
sys.exit(1)
else:
print("No augmentations specified.")
sys.exit(1)
augmenter = Compose(augmentations)
# Process each audio file
for audio_file in audio_files:
try:
# Load audio file
y, sr = librosa.load(
audio_file, sr=sampling_rate, mono=convert_mono, res_type="kaiser_best"
)
# Apply augmentations
y_aug = augmenter(samples=y, sample_rate=sr)
# Save augmented audio file
output_file = os.path.join(output_dir, os.path.basename(audio_file))
sf.write(output_file, y_aug, sr)
print(f"Saved augmented file '{output_file}'.")
except Exception as e:
print(f"Error processing '{audio_file}': {e}")
if __name__ == "__main__":
main()
Usage Instructions:
-
Ensure Dependencies Are Installed:
-
Run the Script with Desired Parameters:
-
List Available Augmentations:
Notes:
- The script processes all audio files with the specified extensions in the input directory.
- Augmentations are applied in the order they are provided.
- The script includes comprehensive error handling to ensure robustness.
- The output files maintain the original filenames and are saved in the specified output directory.
- Ensure that the input audio files are readable and the output directory is writable.
Example Command:
python audio_augmentation.py \
--input_dir ./input_audio \
--output_dir ./output_audio \
--sampling_rate 22050 \
--mono \
--augmentations time_stretching pitch_shifting
This command reads all supported audio files from ./input_audio, converts them to mono with a sampling rate of 22050 Hz, applies time stretching and pitch shifting, and saves the augmented files to ./output_audio.