File size: 1,713 Bytes
1919bbe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | """
===============================================================================
preprocessing/resampling.py — Audio Loading and Resampling
===============================================================================
"""
import librosa
import numpy as np
import warnings
# Assuming TARGET_SR is defined in a config.py file
# For example: TARGET_SR = 16000
from config import TARGET_SR
def resample_audio(file_path):
"""
Load a WAV file and resample it to the target sampling rate.
Parameters
----------
file_path : str
Path to the .wav audio file.
Returns
-------
audio : np.ndarray
1D numpy array of audio samples, resampled to TARGET_SR.
sr : int
The target sampling rate (always TARGET_SR).
Notes
-----
- librosa.load() with sr=TARGET_SR automatically resamples on load.
- mono=True ensures we get a 1D array (no stereo channels).
- If the file is already at TARGET_SR, no resampling is performed (fast path).
"""
try:
# librosa.load automatically handles resampling if sr != native_sr
# the reseon I used "kaiser_best" is that it filter to prevent aliasing
audio, sr = librosa.load(
file_path,
sr=TARGET_SR,
mono=True, # Ensure 1D array for CNN
res_type="kaiser_best"
)
# Safety check: if audio is completely empty
if audio.size == 0:
warnings.warn(f"Warning: Loaded audio from {file_path} is completely empty.")
return audio, sr
except Exception as e:
raise RuntimeError(f"Failed to load or resample audio file at {file_path}. Error: {e}") |