File size: 2,076 Bytes
950fb64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()