File size: 4,728 Bytes
0468ff5 | 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """
Audio Utilities
Common audio processing functions for loading, preprocessing, and segmentation.
"""
import io
import base64
import numpy as np
import librosa
import soundfile as sf
from pathlib import Path
from typing import Union, Tuple, Optional
import tempfile
import os
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import SAMPLE_RATE, DURATION, TEMP_DIR
def load_audio(
source: Union[str, Path, bytes],
sr: int = SAMPLE_RATE,
mono: bool = True
) -> Tuple[np.ndarray, int]:
"""
Load audio from file path, bytes, or base64 string.
Args:
source: File path, raw bytes, or base64-encoded audio
sr: Target sample rate
mono: Convert to mono if True
Returns:
Tuple of (audio_array, sample_rate)
"""
if isinstance(source, (str, Path)):
# Load from file path
audio, sample_rate = librosa.load(source, sr=sr, mono=mono)
elif isinstance(source, bytes):
# Load from bytes
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp.write(source)
tmp_path = tmp.name
try:
audio, sample_rate = librosa.load(tmp_path, sr=sr, mono=mono)
finally:
os.unlink(tmp_path)
else:
raise ValueError(f"Unsupported source type: {type(source)}")
return audio, sample_rate
def decode_base64_audio(
audio_base64: str,
audio_format: str = "wav",
sr: int = SAMPLE_RATE,
mono: bool = True
) -> Tuple[np.ndarray, int]:
"""
Decode base64-encoded audio and load it.
Args:
audio_base64: Base64-encoded audio string
audio_format: Audio format (wav, mp3, etc.)
sr: Target sample rate
mono: Convert to mono if True
Returns:
Tuple of (audio_array, sample_rate)
"""
audio_bytes = base64.b64decode(audio_base64)
return load_audio(audio_bytes, sr=sr, mono=mono)
def preprocess_audio(
audio: np.ndarray,
sr: int = SAMPLE_RATE,
normalize: bool = True,
trim_silence: bool = True,
top_db: int = 20
) -> np.ndarray:
"""
Preprocess audio: normalize amplitude and optionally trim silence.
Args:
audio: Audio array
sr: Sample rate
normalize: Normalize amplitude to [-1, 1]
trim_silence: Remove leading/trailing silence
top_db: Threshold for silence trimming
Returns:
Preprocessed audio array
"""
# Trim silence
if trim_silence:
audio, _ = librosa.effects.trim(audio, top_db=top_db)
# Normalize
if normalize:
max_val = np.max(np.abs(audio))
if max_val > 0:
audio = audio / max_val
return audio
def segment_audio(
audio: np.ndarray,
sr: int = SAMPLE_RATE,
segment_duration: float = DURATION,
overlap: float = 0.5
) -> list:
"""
Segment audio into fixed-length chunks.
Args:
audio: Audio array
sr: Sample rate
segment_duration: Duration of each segment in seconds
overlap: Overlap ratio between segments (0-1)
Returns:
List of audio segments
"""
segment_samples = int(segment_duration * sr)
hop_samples = int(segment_samples * (1 - overlap))
segments = []
start = 0
while start + segment_samples <= len(audio):
segment = audio[start:start + segment_samples]
segments.append(segment)
start += hop_samples
# Handle last segment if there's remaining audio
if start < len(audio):
# Pad the last segment if needed
last_segment = audio[start:]
if len(last_segment) >= segment_samples // 2: # Only if at least half length
padded = np.zeros(segment_samples)
padded[:len(last_segment)] = last_segment
segments.append(padded)
return segments
def ensure_length(
audio: np.ndarray,
target_length: int,
pad_mode: str = "constant"
) -> np.ndarray:
"""
Ensure audio has exact target length by padding or truncating.
Args:
audio: Audio array
target_length: Target number of samples
pad_mode: Padding mode ('constant', 'reflect', etc.)
Returns:
Audio array with exact target length
"""
if len(audio) > target_length:
return audio[:target_length]
elif len(audio) < target_length:
padding = target_length - len(audio)
return np.pad(audio, (0, padding), mode=pad_mode)
return audio
def get_audio_duration(audio: np.ndarray, sr: int = SAMPLE_RATE) -> float:
"""Get duration of audio in seconds."""
return len(audio) / sr
|