46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
import numpy as np
|
|
|
|
class PythonToolsEngine:
|
|
@staticmethod
|
|
def normalize_peak(y: np.ndarray, target_db: float = 0.0) -> np.ndarray:
|
|
"""Peak normalize audio array to target_db (0 dB default)."""
|
|
if len(y) == 0:
|
|
return y
|
|
max_val = np.max(np.abs(y))
|
|
if max_val == 0:
|
|
return y
|
|
target_amp = 10 ** (target_db / 20.0)
|
|
gain = target_amp / max_val
|
|
return y * gain
|
|
|
|
@staticmethod
|
|
def invert_phase(y: np.ndarray) -> np.ndarray:
|
|
"""Invert audio phase (180 degree flip)."""
|
|
return -1.0 * y
|
|
|
|
@staticmethod
|
|
def swap_channels(y: np.ndarray) -> np.ndarray:
|
|
"""Swap Left and Right channels for stereo audio."""
|
|
if y.ndim < 2 or y.shape[0] < 2:
|
|
return y
|
|
swapped = np.copy(y)
|
|
swapped[[0, 1]] = swapped[[1, 0]]
|
|
return swapped
|
|
|
|
@staticmethod
|
|
def generate_synth_wave(wave_type: str = "sine", freq: float = 440.0, duration: float = 2.0, sr: int = 44100) -> np.ndarray:
|
|
"""Generate pure synthesized waveform array (sine, square, sawtooth)."""
|
|
num_samples = int(duration * sr)
|
|
t = np.linspace(0, duration, num_samples, endpoint=False)
|
|
|
|
if wave_type == "sine":
|
|
audio = np.sin(2 * np.pi * freq * t)
|
|
elif wave_type == "square":
|
|
audio = np.sign(np.sin(2 * np.pi * freq * t))
|
|
elif wave_type == "sawtooth":
|
|
audio = 2 * (t * freq - np.floor(0.5 + t * freq))
|
|
else:
|
|
audio = np.sin(2 * np.pi * freq * t)
|
|
|
|
return audio.astype(np.float32)
|