这个警告是 TorchAudio 在处理 MP3 文件时的一个已知问题。有几种方法可以解决:
方案1: 预处理音频为 WAV 格式
最简单的解决方案是先把 MP3 转换为 WAV 格式:
import ffmpeg
def convert_to_wav(mp3_path, wav_path):
"""将 MP3 转换为 WAV 格式"""
stream = ffmpeg.input(mp3_path)
stream = ffmpeg.output(stream, wav_path, acodec='pcm_s16le', ar='16000')
ffmpeg.run(stream, overwrite_output=True)
# 在主程序中使用
def main(infile: Path, outfile: Path):
# 先转换音频格式
wav_path = infile.with_suffix('.wav')
convert_to_wav(str(infile), str(wav_path))
# 后续处理使用 wav_path
print("1/4 ASR ...")
asr_segs = transcribe(wav_path)
# ...其余代码不变...
方案2: 使用 soundfile 替代 TorchAudio
修改 pyannote 的音频加载后端:
import torch
from pyannote.audio import Pipeline
import soundfile as sf
# 在使用 Pipeline 之前设置
torch.set_audio_backend("soundfile")
def diarize(audio_path)-> list[dict]:
pipeline = Pipeline.from_pretrained(
DIAR_MODEL_DIR,
use_auth_token=None
)
# 其余代码不变...
方案3: 忽略警告(如果功能正常)
如果功能正常,只是不想看到警告,可以:
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="soundfile_backend")
# 或者在代码块中临时忽略
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# 你的代码...
方案4: 完整的音频预处理函数
这是一个更健壮的解决方案,包含格式转换和重采样:
import ffmpeg
import numpy as np
from pathlib import Path
def preprocess_audio(input_path: Path, target_sr: int = 16000) -> Path:
"""
预处理音频文件:
1. 转换为 WAV
2. 重采样到目标采样率
3. 转换为单声道
4. 标准化音量
"""
output_path = input_path.with_stem(input_path.stem + "_processed").with_suffix('.wav')
try:
# ffmpeg 处理流程
stream = (
ffmpeg
.input(str(input_path))
.output(
str(output_path),
acodec='pcm_s16le', # 16位 PCM
ac=1, # 单声道
ar=str(target_sr), # 采样率
audio_bitrate='16k' # 比特率
)
.overwrite_output()
)
# 运行转换
stream.run(capture_stdout=True, capture_stderr=True)
print(f"音频预处理完成: {output_path}")
return output_path
except ffmpeg.Error as e:
print(f"音频处理失败: {e.stderr.decode()}")
raise
# 在主程序中使用
def main(infile: Path, outfile: Path):
# 预处理音频
processed_audio = preprocess_audio(infile)
print("1/4 ASR ...")
asr_segs = transcribe(processed_audio)
print("2/4 Diarization ...")
spk_segs = diarize(processed_audio)
# ...其余代码不变...
# 可选:处理完删除临时文件
processed_audio.unlink()
补充说明
- 如果使用方案1或4,需要安装 ffmpeg-python:
pip install ffmpeg-python
- 确保系统已安装 ffmpeg:
# Ubuntu/Debian
sudo apt-get install ffmpeg
# macOS
brew install ffmpeg
# Windows
# 下载 ffmpeg 并添加到系统环境变量
- 音频预处理的参数可以根据需要调整:
- 采样率 (ar): 16000Hz 通常足够语音识别
- 声道数 (ac): 1 表示单声道
- 位深度: pcm_s16le 表示16位
这些解决方案中,推荐使用方案4,因为它不仅解决了警告问题,还能确保音频格式的一致性,提高后续处理的稳定性。如果你的音频文件质量本身就很好,用方案1也是不错的选择。