Whisper语音识别实战:用Python实现高精度中文语音转文字工具

AI教程 2026-06-16

OpenAI开源的Whisper模型是目前最强大的通用语音识别系统之一,支持包括中文在内的多种语言。本文将带您从零开始,构建一个完整的语音转文字工具。

环境准备

首先安装必要的依赖:

pip install openai-whisper torch ffmpeg-python

同时需要确保系统中安装了FFmpeg:

# Ubuntu/Debian
sudo apt install ffmpeg

# macOS
brew install ffmpeg

基础语音识别

以下是使用Whisper进行中文语音识别的基础代码:

import whisper
model = whisper.load_model("medium")
result = model.transcribe(
    "meeting_recording.mp3",
    language="zh",
    task="transcribe",
    verbose=True
)
print(result["text"])

支持多种音频格式

添加格式转换支持,兼容MP3/WAV/M4A/MP4等格式:

import whisper, ffmpeg, tempfile, os

def transcribe_audio(input_path, model_size="medium"):
    model = whisper.load_model(model_size)
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
        temp_path = tmp.name
    try:
        ffmpeg.input(input_path).output(
            temp_path, acodec="pcm_s16le", ac=1, ar="16000"
        ).run(quiet=True, overwrite_output=True)
        result = model.transcribe(
            temp_path, language="zh",
            beam_size=5, best_of=5
        )
        return result["text"]
    finally:
        os.unlink(temp_path)

# 使用示例
text = transcribe_audio("interview.mp4")
print(text)

生成SRT字幕文件

def generate_srt(audio_path, srt_path="output.srt"):
    model = whisper.load_model("medium")
    result = model.transcribe(audio_path, language="zh")
    with open(srt_path, "w", encoding="utf-8") as f:
        for i, seg in enumerate(result["segments"], 1):
            start = fmt_time(seg["start"])
            end = fmt_time(seg["end"])
            text = seg["text"].strip()
            f.write(f"{i}\n{start} --> {end}\n{text}\n\n")
    print(f"字幕已保存到 {srt_path}")

def fmt_time(sec):
    h = int(sec // 3600)
    m = int((sec % 3600) // 60)
    s = int(sec % 60)
    ms = int((sec % 1) * 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

generate_srt("lecture.mp3")

批量处理目录中的音频文件

import os, whisper

def batch_transcribe(directory, model_size="medium"):
    model = whisper.load_model(model_size)
    supported = (".mp3", ".wav", ".m4a", ".ogg", ".mp4", ".avi", ".mov")
    for fn in os.listdir(directory):
        if fn.lower().endswith(supported):
            fp = os.path.join(directory, fn)
            print(f"正在处理: {fn}")
            result = model.transcribe(fp, language="zh")
            txt = os.path.join(directory, f"{os.path.splitext(fn)[0]}.txt")
            with open(txt, "w", encoding="utf-8") as f:
                f.write(result["text"])
            print(f"完成: {txt}")

batch_transcribe("./audio_files")

总结

Whisper在中文语音识别上的准确率令人印象深刻,尤其是在使用medium或large模型时。通过上述代码,您可以快速构建一个实用的语音转文字工具,适用于会议记录、视频字幕生成、播客转写等多种场景。

进阶优化方向:
1. 使用VAD(语音活动检测)预处理提高准确率
2. 结合语言模型进行后处理纠错
3. 使用Whisper API进行更低延迟的云端部署

©️版权声明:若无特殊声明,本站所有文章版权均归AI工具集原创和所有,未经许可,任何个人、媒体、网站、团体不得转载、抄袭或以其他方式复制发表本站内容,或在非我站所属的服务器上建立镜像。否则,我站将依法保留追究相关法律责任的权利。

相关文章