forked from goarstne/mp3-matcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio_processor.py
More file actions
289 lines (233 loc) · 10.4 KB
/
Copy pathaudio_processor.py
File metadata and controls
289 lines (233 loc) · 10.4 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
Audio Volume Normalizer - Audio Processing Module
This module handles audio processing operations including:
- Loading audio files (MP3 and WAV)
- Detecting loudness levels
- Normalizing audio volume
"""
import logging
import os
from typing import Dict, List, Tuple, Optional, Callable
import numpy as np
from pydub import AudioSegment
logger = logging.getLogger(__name__)
class AudioProcessor:
"""Handles audio processing for the Audio Volume Normalizer."""
def __init__(self):
"""Initialize the AudioProcessor."""
self.loudness_cache: Dict[str, float] = {}
self.encoding_cache: Dict[str, Dict[str, any]] = {}
self.max_loudness: float = 0.0
self.reference_file: Optional[str] = None
self.reference_encoding: Optional[Dict[str, any]] = None
def load_audio(self, file_path: str) -> Optional[AudioSegment]:
"""
Load an audio file (MP3 or WAV) into a pydub AudioSegment.
Args:
file_path: Path to the audio file
Returns:
AudioSegment object or None if loading fails
Raises:
FileNotFoundError: If the file doesn't exist
"""
if not os.path.exists(file_path):
logger.error(f"File not found: {file_path}")
raise FileNotFoundError(f"File not found: {file_path}")
try:
logger.debug(f"Loading audio file: {file_path}")
# Determine file type and load accordingly
if file_path.lower().endswith('.mp3'):
audio = AudioSegment.from_mp3(file_path)
elif file_path.lower().endswith('.wav'):
audio = AudioSegment.from_wav(file_path)
else:
logger.error(f"Unsupported file format: {file_path}")
return None
return audio
except Exception as e:
# Log the error but don't crash the application
logger.error(f"Failed to load audio file {file_path}: {e}")
return None
def calculate_loudness(self, audio: AudioSegment) -> float:
"""
Calculate the loudness of an audio segment.
This uses the RMS (Root Mean Square) method to calculate loudness,
which is a common way to measure the average power of an audio signal.
Args:
audio: pydub AudioSegment
Returns:
Loudness value (higher is louder)
"""
# Convert audio to numpy array for efficient processing
samples = np.array(audio.get_array_of_samples())
# Calculate RMS (Root Mean Square)
rms = np.sqrt(np.mean(np.square(samples.astype(np.float64))))
# Convert to dB (decibels)
if rms > 0:
db = 20 * np.log10(rms)
else:
db = -96.0 # Approximate silence level
return db
def get_encoding_parameters(self, audio: AudioSegment) -> Dict[str, any]:
"""
Extract encoding parameters from an audio segment.
Args:
audio: pydub AudioSegment
Returns:
Dictionary containing encoding parameters
"""
return {
"sample_rate": audio.frame_rate,
"channels": audio.channels,
"bits_per_sample": audio.sample_width * 8,
"format": "mp3" if hasattr(audio, "_data") and audio.channels > 0 else "wav"
}
def analyze_file(self, file_path: str) -> Optional[float]:
"""
Analyze an audio file to determine its loudness and encoding parameters.
Args:
file_path: Path to the audio file
Returns:
Loudness value or None if analysis fails
"""
try:
audio = self.load_audio(file_path)
if audio is None:
return None
# Get encoding parameters
encoding = self.get_encoding_parameters(audio)
self.encoding_cache[file_path] = encoding
# Calculate loudness
loudness = self.calculate_loudness(audio)
self.loudness_cache[file_path] = loudness
# Update max loudness if this file is louder
if loudness > self.max_loudness:
self.max_loudness = loudness
self.reference_file = file_path
self.reference_encoding = encoding
logger.debug(f"New reference file: {file_path} (loudness: {loudness:.2f} dB)")
logger.debug(f"Reference encoding: {self.reference_encoding}")
return loudness
except Exception as e:
logger.error(f"Error analyzing file {file_path}: {e}")
return None
def analyze_files(
self,
file_paths: List[str],
progress_callback: Optional[Callable[[int, int, str], None]] = None
) -> Tuple[Dict[str, float], Dict[str, Dict[str, any]]]:
"""
Analyze multiple audio files to determine their loudness and encoding parameters.
Args:
file_paths: List of paths to audio files (MP3 and WAV)
progress_callback: Optional callback function to report progress
Args: (current_index, total_count, current_file)
Returns:
Tuple of (loudness_cache, encoding_cache):
- loudness_cache: Dictionary mapping file paths to loudness values
- encoding_cache: Dictionary mapping file paths to encoding parameters
"""
self.loudness_cache = {}
self.encoding_cache = {}
self.max_loudness = -96.0 # Start with silence level
self.reference_file = None
self.reference_encoding = None
total_files = len(file_paths)
for i, file_path in enumerate(file_paths):
if progress_callback:
progress_callback(i, total_files, file_path)
loudness = self.analyze_file(file_path)
if loudness is not None:
logger.debug(f"File {file_path}: loudness = {loudness:.2f} dB")
if progress_callback:
progress_callback(total_files, total_files, "Analysis complete")
if self.reference_file:
logger.info(f"Reference file: {self.reference_file} (loudness: {self.max_loudness:.2f} dB)")
else:
logger.warning("No valid reference file found")
return (self.loudness_cache, self.encoding_cache)
def normalize_file(
self,
file_path: str,
target_loudness: Optional[float] = None
) -> Optional[AudioSegment]:
"""
Normalize the volume of an audio file.
Args:
file_path: Path to the audio file (MP3 or WAV)
target_loudness: Target loudness in dB (if None, uses max_loudness)
Returns:
Normalized AudioSegment or None if normalization fails
"""
if target_loudness is None:
if self.max_loudness == 0:
logger.error("No reference loudness available")
return None
target_loudness = self.max_loudness
try:
# Load the audio file
audio = self.load_audio(file_path)
if audio is None:
return None
# Get current loudness
current_loudness = self.loudness_cache.get(file_path)
if current_loudness is None:
current_loudness = self.calculate_loudness(audio)
# Calculate the gain needed
gain_db = target_loudness - current_loudness
# Apply the gain
if abs(gain_db) > 0.1: # Only apply if the difference is significant
logger.debug(f"Normalizing {file_path}: applying {gain_db:.2f} dB gain")
normalized_audio = audio.apply_gain(gain_db)
return normalized_audio
else:
logger.debug(f"File {file_path} already at target loudness")
return audio
except Exception as e:
logger.error(f"Error normalizing file {file_path}: {e}")
return None
def normalize_files(
self,
file_paths: List[str],
file_manager: any, # Avoid circular import
progress_callback: Optional[Callable[[int, int, str], None]] = None
) -> Tuple[int, int]:
"""
Normalize multiple audio files to match the loudest file.
Args:
file_paths: List of paths to audio files (MP3 and WAV)
file_manager: FileManager instance for saving files
progress_callback: Optional callback function to report progress
Args: (current_index, total_count, current_file)
Returns:
Tuple of (number of successful normalizations, number of failed normalizations)
"""
if not self.reference_file:
logger.error("No reference file available for normalization")
return (0, 0)
total_files = len(file_paths)
success_count = 0
fail_count = 0
for i, file_path in enumerate(file_paths):
if progress_callback:
progress_callback(i, total_files, file_path)
# Skip the reference file if it's already at max loudness
if file_path == self.reference_file:
logger.debug(f"Skipping reference file: {file_path}")
success_count += 1
continue
# Normalize the file
normalized_audio = self.normalize_file(file_path)
if normalized_audio is None:
logger.error(f"Failed to normalize {file_path}")
fail_count += 1
continue
# Save the normalized file with reference encoding
if file_manager.save_normalized_file(file_path, normalized_audio, self.reference_encoding):
success_count += 1
else:
fail_count += 1
if progress_callback:
progress_callback(total_files, total_files, "Normalization complete")
logger.info(f"Normalized {success_count} files, {fail_count} failed")
return (success_count, fail_count)