File size: 2,460 Bytes
277fc1d | 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 | """音频解码模块:从视频/音频文件中提取单声道时域信号。
依赖系统已安装 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)
|