Test / app /services /audio_processor.py
Drizzy
h
950fb64
Raw
History Blame Contribute Delete
2.08 kB
import librosa
import numpy as np
import soundfile as sf
import os
from pydub import AudioSegment
from ..config import settings
class AudioProcessor:
@staticmethod
def get_waveform_data(filepath: str, points: int = 100):
"""Generates simplified waveform data for the frontend visualizer."""
try:
y, sr = librosa.load(filepath, sr=None)
# Resample to 'points' number of data points
if len(y) > points:
# Take the max amplitude in each segment
segment_size = len(y) // points
waveform = [float(np.max(np.abs(y[i*segment_size : (i+1)*segment_size]))) for i in range(points)]
else:
waveform = [float(val) for val in y]
# Normalize to 0-1
max_val = max(waveform) if waveform else 1
waveform = [round(val / max_val, 3) for val in waveform]
return waveform
except Exception as e:
print(f"Error generating waveform: {e}")
return [0] * points
@staticmethod
def convert_to_mp3(wav_path: str):
"""Converts WAV to MP3 for better streaming performance."""
mp3_path = wav_path.replace(".wav", ".mp3")
try:
audio = AudioSegment.from_wav(wav_path)
audio.export(mp3_path, format="mp3", bitrate="192k")
return mp3_path
except Exception as e:
print(f"Error converting to mp3: {e}")
return None
@staticmethod
def get_metadata(filepath: str):
"""Extracts basic audio metadata."""
try:
y, sr = librosa.load(filepath, sr=None)
duration = librosa.get_duration(y=y, sr=sr)
return {
"duration_sec": round(duration, 2),
"duration_str": f"{int(duration // 60)}:{int(duration % 60):02d}",
"sample_rate": sr
}
except Exception as e:
print(f"Error extracting metadata: {e}")
return None
audio_processor = AudioProcessor()