Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
+266
@@ -0,0 +1,266 @@
|
||||
"""音频输入、预处理与 WAV 编解码。
|
||||
|
||||
设计取舍:PCM WAV 用标准库 ``wave`` 读取,保证零第三方依赖也能跑通主链路;
|
||||
若环境里装了 ``soundfile``,则额外支持 MP3 / FLAC / OGG 等格式。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import math
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from .config import DEFAULT, Config
|
||||
|
||||
__all__ = [
|
||||
"read_audio",
|
||||
"read_wav_bytes",
|
||||
"write_wav",
|
||||
"encode_wav_bytes",
|
||||
"resample",
|
||||
"bandpass",
|
||||
"denoise",
|
||||
"normalize",
|
||||
"trim_silence",
|
||||
"preprocess",
|
||||
"rms_db",
|
||||
"frame_signal",
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 读取
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _pcm_to_float(raw: bytes, sampwidth: int, n_channels: int) -> np.ndarray:
|
||||
"""把交错 PCM 字节流转成 [-1, 1] 的 float32 单声道波形。"""
|
||||
if sampwidth == 1:
|
||||
# 8-bit WAV 是无符号偏移码
|
||||
data = np.frombuffer(raw, dtype=np.uint8).astype(np.float32)
|
||||
data = (data - 128.0) / 128.0
|
||||
elif sampwidth == 2:
|
||||
data = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
|
||||
elif sampwidth == 3:
|
||||
b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
|
||||
# 小端 24-bit 有符号:补齐到 32-bit 再右移 8 位
|
||||
val = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
|
||||
val = np.where(val >= (1 << 23), val - (1 << 24), val)
|
||||
data = val.astype(np.float32) / 8388608.0
|
||||
elif sampwidth == 4:
|
||||
data = np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0
|
||||
else:
|
||||
raise ValueError(f"不支持的 WAV 位深: {sampwidth * 8} bit")
|
||||
|
||||
if n_channels > 1:
|
||||
data = data.reshape(-1, n_channels).mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32)
|
||||
|
||||
|
||||
def read_wav_bytes(blob: bytes) -> tuple[np.ndarray, int]:
|
||||
"""解析内存中的 WAV 字节流,返回 (单声道 float32 波形, 采样率)。"""
|
||||
with wave.open(io.BytesIO(blob), "rb") as wf:
|
||||
sr = wf.getframerate()
|
||||
n_channels = wf.getnchannels()
|
||||
sampwidth = wf.getsampwidth()
|
||||
raw = wf.readframes(wf.getnframes())
|
||||
if not raw:
|
||||
raise ValueError("WAV 数据为空")
|
||||
return _pcm_to_float(raw, sampwidth, n_channels), sr
|
||||
|
||||
|
||||
def _read_via_soundfile(path: Path) -> tuple[np.ndarray, int]:
|
||||
import soundfile as sf # 可选依赖
|
||||
|
||||
data, sr = sf.read(str(path), dtype="float32", always_2d=False)
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32), int(sr)
|
||||
|
||||
|
||||
def read_audio(source: str | Path | bytes) -> tuple[np.ndarray, int]:
|
||||
"""读取音频文件或字节流,返回 (单声道 float32 波形, 采样率)。
|
||||
|
||||
优先用标准库解析 WAV;失败且装了 soundfile 时,再尝试其它容器格式。
|
||||
"""
|
||||
if isinstance(source, bytes):
|
||||
try:
|
||||
return read_wav_bytes(source)
|
||||
except Exception:
|
||||
if not _has_soundfile():
|
||||
raise
|
||||
data, sr = _read_via_soundfile_bytes(source)
|
||||
return data, sr
|
||||
|
||||
path = Path(source)
|
||||
try:
|
||||
return read_wav_bytes(path.read_bytes())
|
||||
except Exception:
|
||||
if not _has_soundfile():
|
||||
raise
|
||||
return _read_via_soundfile(path)
|
||||
|
||||
|
||||
def _has_soundfile() -> bool:
|
||||
try:
|
||||
import soundfile # noqa: F401
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _read_via_soundfile_bytes(blob: bytes) -> tuple[np.ndarray, int]:
|
||||
import soundfile as sf
|
||||
|
||||
data, sr = sf.read(io.BytesIO(blob), dtype="float32", always_2d=False)
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=1)
|
||||
return np.ascontiguousarray(data, dtype=np.float32), int(sr)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 写出
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _float_to_pcm16(x: np.ndarray) -> bytes:
|
||||
clipped = np.clip(x, -1.0, 1.0)
|
||||
return (clipped * 32767.0).astype("<i2").tobytes()
|
||||
|
||||
|
||||
def encode_wav_bytes(x: np.ndarray, sr: int) -> bytes:
|
||||
"""把波形编码为 16-bit PCM WAV 字节流(用于 HTTP 响应 / 前端回放)。"""
|
||||
buf = io.BytesIO()
|
||||
with wave.open(buf, "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(int(sr))
|
||||
wf.writeframes(_float_to_pcm16(x))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def write_wav(path: str | Path, x: np.ndarray, sr: int) -> None:
|
||||
"""把波形写成 16-bit PCM WAV 文件。"""
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(encode_wav_bytes(x, sr))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 预处理
|
||||
# --------------------------------------------------------------------------- #
|
||||
def resample(x: np.ndarray, sr: int, target_sr: int) -> np.ndarray:
|
||||
"""多相滤波重采样(有理数比例),比线性插值保真。"""
|
||||
if sr == target_sr or x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
g = math.gcd(int(sr), int(target_sr))
|
||||
up, down = target_sr // g, sr // g
|
||||
return signal.resample_poly(x, up, down).astype(np.float32)
|
||||
|
||||
|
||||
def bandpass(
|
||||
x: np.ndarray, sr: int, low_hz: float, high_hz: float, order: int = 4
|
||||
) -> np.ndarray:
|
||||
"""零相位 Butterworth 带通滤波。
|
||||
|
||||
哼唱的有效能量集中在 60–2000 Hz;低于 60 Hz 多为桌面震动/直流漂移,
|
||||
高于 2000 Hz 多为齿音与房间噪声。截止频率贴近 Nyquist 时自动退化为低通。
|
||||
"""
|
||||
if x.size < 32:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
nyq = sr / 2.0
|
||||
high = min(high_hz, nyq * 0.95)
|
||||
low = max(low_hz, 1e-3)
|
||||
if low >= high:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
sos = signal.butter(order, [low, high], btype="bandpass", fs=sr, output="sos")
|
||||
return signal.sosfiltfilt(sos, x).astype(np.float32)
|
||||
|
||||
|
||||
def denoise(x: np.ndarray, window: int = 3) -> np.ndarray:
|
||||
"""滑动均值去噪。窗口很小,只削高频毛刺,不破坏基频轮廓。"""
|
||||
if window <= 1 or x.size < window:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
kernel = np.ones(int(window), dtype=np.float32) / float(window)
|
||||
return np.convolve(x, kernel, mode="same").astype(np.float32)
|
||||
|
||||
|
||||
def rms_db(x: np.ndarray) -> float:
|
||||
"""整体 RMS 的分贝值;空信号或全零信号返回 -inf。"""
|
||||
if x.size == 0:
|
||||
return float("-inf")
|
||||
rms = float(np.sqrt(np.mean(np.square(x, dtype=np.float64))))
|
||||
if rms <= 0.0:
|
||||
return float("-inf")
|
||||
return 20.0 * math.log10(rms)
|
||||
|
||||
|
||||
def normalize(x: np.ndarray, target_rms: float = 0.06) -> np.ndarray:
|
||||
"""按 RMS 归一化并限幅,使音量不同的录音具有可比性。"""
|
||||
if x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
rms = float(np.sqrt(np.mean(np.square(x, dtype=np.float64))))
|
||||
if rms < 1e-8:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
y = x * (target_rms / rms)
|
||||
return np.clip(y, -1.0, 1.0).astype(np.float32)
|
||||
|
||||
|
||||
def trim_silence(
|
||||
x: np.ndarray,
|
||||
sr: int,
|
||||
threshold_db: float = -45.0,
|
||||
padding_ms: float = 50.0,
|
||||
) -> np.ndarray:
|
||||
"""裁掉首尾静音(相对峰值门限),保留少量留白避免削掉起音。"""
|
||||
if x.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
win = max(1, int(0.02 * sr)) # 20 ms 能量窗
|
||||
n = x.size // win
|
||||
if n < 2:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
energy = np.square(x[: n * win], dtype=np.float64).reshape(n, win).mean(axis=1)
|
||||
peak = float(energy.max())
|
||||
if peak <= 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
floor = peak * (10.0 ** (threshold_db / 10.0))
|
||||
active = np.flatnonzero(energy >= floor)
|
||||
if active.size == 0:
|
||||
return np.asarray(x, dtype=np.float32)
|
||||
pad = int(padding_ms / 1000.0 * sr)
|
||||
start = max(0, active[0] * win - pad)
|
||||
stop = min(x.size, (active[-1] + 1) * win + pad)
|
||||
return np.ascontiguousarray(x[start:stop], dtype=np.float32)
|
||||
|
||||
|
||||
def preprocess(
|
||||
x: np.ndarray,
|
||||
sr: int,
|
||||
cfg: Config = DEFAULT,
|
||||
*,
|
||||
do_bandpass: bool = True,
|
||||
do_denoise: bool = True,
|
||||
do_trim: bool = True,
|
||||
) -> np.ndarray:
|
||||
"""完整预处理链:重采样 → 去噪 → 带通 → 静音裁剪 → 归一化。
|
||||
|
||||
开关参数用于噪声鲁棒性实验中的“预处理开/关”对照。
|
||||
"""
|
||||
y = resample(x, sr, cfg.sample_rate)
|
||||
if do_denoise:
|
||||
y = denoise(y, cfg.denoise_window)
|
||||
if do_bandpass:
|
||||
y = bandpass(y, cfg.sample_rate, cfg.band_low_hz, cfg.band_high_hz, cfg.band_order)
|
||||
if do_trim:
|
||||
y = trim_silence(y, cfg.sample_rate, cfg.trim_threshold_db, cfg.trim_padding_ms)
|
||||
return normalize(y, cfg.target_rms)
|
||||
|
||||
|
||||
def frame_signal(x: np.ndarray, frame_len: int, hop: int) -> np.ndarray:
|
||||
"""分帧,返回形状 (n_frames, frame_len) 的视图(不足一帧则丢弃)。"""
|
||||
if x.size < frame_len:
|
||||
return np.empty((0, frame_len), dtype=np.float32)
|
||||
n_frames = 1 + (x.size - frame_len) // hop
|
||||
idx = np.arange(frame_len)[None, :] + hop * np.arange(n_frames)[:, None]
|
||||
return np.ascontiguousarray(x[idx])
|
||||
Reference in New Issue
Block a user