Download audio_decoder.py from Vampont/NVH: direct link, hf CLI and curl.
- Browser
- Download file 2.46 kB
-
https://huggingface.co/spaces/Vampont/NVH/resolve/main/audio_decoder.py
- Command line
-
hf download hf://spaces/Vampont/NVH/audio_decoder.py
-
curl -L -o audio_decoder.py https://huggingface.co/spaces/Vampont/NVH/resolve/main/audio_decoder.py
2.46 kB
| """音频解码模块:从视频/音频文件中提取单声道时域信号。 | |
| 依赖系统已安装 ffmpeg(需在 PATH 中)。 | |
| """ | |
| import subprocess | |
| import tempfile | |
| import os | |
| from math import gcd | |
| from pathlib import Path | |
| import numpy as np | |
| import soundfile as sf | |
| DEFAULT_SR = 44100 | |
| _NATIVE_AUDIO_EXTS = {".wav", ".flac", ".ogg", ".aiff", ".aif"} | |
| def decode_audio(file_path: str, target_sr: int = DEFAULT_SR) -> tuple: | |
| """ | |
| 从任意音频/视频文件解码,返回单声道 float32 时域信号。 | |
| Parameters | |
| ---------- | |
| file_path : str | |
| 输入文件路径,支持 .mp4 .mov .avi .mkv .mp3 .m4a .wav .flac 等。 | |
| target_sr : int | |
| 目标采样率,默认 44100 Hz。 | |
| Returns | |
| ------- | |
| samples : np.ndarray shape (N,) float32,范围约 [-1, 1] | |
| sample_rate : int 实际采样率(== target_sr) | |
| """ | |
| file_path = str(file_path) | |
| ext = Path(file_path).suffix.lower() | |
| if ext not in _NATIVE_AUDIO_EXTS: | |
| wav_path = _ffmpeg_to_wav(file_path, target_sr) | |
| tmp = True | |
| else: | |
| wav_path = file_path | |
| tmp = False | |
| try: | |
| samples, sr = sf.read(wav_path, dtype="float32", always_2d=False) | |
| finally: | |
| if tmp and os.path.exists(wav_path): | |
| os.remove(wav_path) | |
| # 多声道 → 单声道 | |
| if samples.ndim > 1: | |
| samples = samples.mean(axis=1) | |
| # 重采样 | |
| if sr != target_sr: | |
| samples = _resample(samples, sr, target_sr) | |
| return samples.astype(np.float32), target_sr | |
| def _ffmpeg_to_wav(src: str, sr: int) -> str: | |
| """用 ffmpeg 将任意媒体转为单声道 WAV,返回临时文件路径。""" | |
| tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) | |
| tmp_path = tmp.name | |
| tmp.close() | |
| cmd = [ | |
| "ffmpeg", "-y", | |
| "-i", src, | |
| "-ac", "1", | |
| "-ar", str(sr), | |
| "-vn", | |
| tmp_path, | |
| ] | |
| result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| if result.returncode != 0: | |
| raise RuntimeError( | |
| f"ffmpeg 解码失败:\n{result.stderr.decode(errors='replace')}" | |
| ) | |
| return tmp_path | |
| def _resample(samples: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray: | |
| """整数比率重采样(scipy polyphase)。""" | |
| from scipy.signal import resample_poly | |
| g = gcd(orig_sr, target_sr) | |
| return resample_poly(samples, target_sr // g, orig_sr // g).astype(np.float32) | |