想要实现类似豆包或微信的语音输入体验,云端 API 虽准但涉及隐私,本地模型则是免费且离线的优选方案。这里记录一下基于 Faster-Whisper 的本地实时语音转文本部署过程。
环境搭建
在虚拟环境中安装核心依赖即可:
pip install faster-whisper pyaudio
若需 GPU 加速,请确保已正确安装 CUDA 和 cuDNN 环境。没有显卡则默认使用 CPU 推理。
模型下载
Faster-Whisper 支持多种模型规格,根据性能需求选择:
- Tiny/Base/Small:轻量级,速度快
- Medium/Large-v2/v3:精度高,资源消耗大
- Distil-Large-v3:蒸馏版,兼顾速度与效果
手动下载时,进入 Hugging Face 仓库的 "Files and versions" 页面,将 config.json、model.bin、tokenizer.json、vocabulary.json 等关键文件放入同一文件夹。例如下载 large-v3 版本,解压后路径指向该目录即可。
录音与转录脚本
核心逻辑分为两部分:一是通过 pyaudio 采集音频并保存为临时 WAV 文件,二是调用 Whisper 模型进行转录。下面是一个完整的示例代码,包含 GPU 检测与 VAD(语音活动检测)过滤。
# -*- coding: utf-8 -*-
import os
import sys
import time
import wave
import tempfile
import threading
import torch
import pyaudio
from faster_whisper import WhisperModel
AUDIO_BUFFER = 5 # 录音切片时长(秒)
def record_audio(p, device):
# 创建临时文件存储音频
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
filename = f.name
wave_file = wave.open(filename, "wb")
wave_file.setnchannels(int(device["maxInputChannels"]))
wave_file.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wave_file.setframerate(int(device["defaultSampleRate"]))
def callback(in_data, frame_count, time_info, status):
wave_file.writeframes(in_data)
return (in_data, pyaudio.paContinue)
try:
stream = p.open(format=pyaudio.paInt16,
channels=int(device["maxInputChannels"]),
rate=int(device["defaultSampleRate"]),
frames_per_buffer=1024,
input=True,
input_device_index=device["index"],
stream_callback=callback)
time.sleep(AUDIO_BUFFER) # 阻塞主线程进行录音
except Exception as e:
print(f"录音出错:{e}")
finally:
if 'stream' in locals():
stream.stop_stream()
stream.close()
wave_file.close()
return filename
def whisper_audio(filename, model):
"""调用模型进行转录"""
try:
# vad_filter=True 可去掉没说话的静音片段
segments, info = model.transcribe(
filename, beam_size=5,
language="zh",
vad_filter=True,
vad_parameters=dict(min_silence_duration_ms=500)
)
for segment in segments:
print("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))
except Exception as e:
print(f"转录出错:{e}")
finally:
# 转录完成后删除临时文件
if os.path.exists(filename):
os.remove(filename)
def main():
print("正在加载 Whisper 模型...")
# 检查 GPU
if torch.cuda.is_available():
device = "cuda"
compute_type = "float16" # 或者 "int8_float16"
print("使用 GPU (CUDA) 进行推理")
else:
device = "cpu"
compute_type = "int8" # CPU 上推荐用 int8
print("使用 CPU 进行推理")
# 模型路径
model_path = "large-v3"
try:
model = WhisperModel(model_path, device=device, compute_type=compute_type, local_files_only=True)
print("模型加载成功!")
except Exception as e:
print(f"模型加载失败:{e}")
return
with pyaudio.PyAudio() as p:
try:
default_mic = p.get_default_input_device_info()
print(f"\n当前使用的麦克风:{default_mic['name']} (Index: {default_mic['index']})")
print(f"采样率:{default_mic['defaultSampleRate']}, 通道数:{default_mic['maxInputChannels']}")
print("-" * 50)
print("开始持续录音 (按 Ctrl+C 停止)...")
while True:
filename = record_audio(p, default_mic)
thread = threading.Thread(target=whisper_audio, args=(filename, model))
thread.start()
except OSError:
print("未找到默认麦克风,请检查系统声音设置。")
except KeyboardInterrupt:
print("\n停止录音,程序退出。")
except Exception as e:
print(f"\n发生未知错误:{e}")
if __name__ == '__main__':
main()
常见问题排查
1. cuDNN 版本冲突
报错提示 Could not locate cudnn_ops64_9.dll 或 Invalid handle,通常是因为 Faster-Whisper 依赖的 CTranslate2 引擎基于 cuDNN 9.x 编译,而本地环境缺失对应版本。解决方案是降级 ctranslate2:
pip install --force-reinstall ctranslate2==4.4.0
2. CUDA 库缺失
若遇到 cuBLAS failed with status CUBLAS_STATUS_NOT_SUPPORTED,说明虚拟环境调用的 CUDA 版本与 PyTorch 不匹配。例如 PyTorch 自带 CUDA 11.8,但系统环境变量可能指向其他版本。此时需要找到虚拟环境中 torch/lib 下的 cublas64_11.dll,复制一份并重命名为 cublas64_12.dll 以兼容调用。
3. VAD 过滤器报错
若提示 Applying the VAD filter requires the onnxruntime package,请将 onnxruntime 版本降低至稳定版:
pip install onnxruntime==1.19.2
完成上述配置后,即可运行脚本实现本地实时语音转文字。

