导读

如果你有一段录音(会议、播客、课堂笔记),想快速把它变成文字稿——以前你可能要花钱买在线转写服务,或者花好几天搭一套复杂的深度学习系统。今天我们要用的 Whisper 正好解决了这个问题:它是 OpenAI 在 2022 年开源的多语言语音识别模型,可以在你自己的电脑上离线运行,免费、隐私有保障,支持中文在内的 99 种语言。

本篇从零开始,帮你把整个环境搭起来。只需要一个前置依赖 ffmpeg,剩下的通过 pip 一行命令搞定。文末提供一键脚本,Windows / macOS / Linux 都能跑。


一、Whisper 是什么?

Whisper 是 OpenAI 发布的一个自动语音识别(ASR,Automatic Speech Recognition)模型。它用来自 68 万小时多语言+多标签数据的训练数据训练的,核心特点包括:

  • 开源免费:Apache 2.0 许可,可以随意修改和商业使用
  • 多语言:支持中文、英文、日语等 99 种语言的识别和翻译
  • 本地运行:不需要联网调用 API,装好就在本机跑,保护隐私
  • 开箱即用:命令行工具 + Python API 双接口,小白也能上手

GitHub 仓库地址:https://github.com/openai/whisper (国内用户访问不畅时,可以加 ghfast.top 前缀代理:https://ghfast.top/https://github.com/openai/whisper

模型规格一览

Whisper 提供了多个规格(规格越大,准确率越高,但需要的内存和速度越慢)。官方共有以下模型供选择:

模型参数量VRAM 需求参考速度适用场景
tiny39M~1 GB最快快速原型验证
base74M~1 GB日常轻度使用
small244M~2 GB中等较好中文效果
medium769M~5 GB较慢高准确率要求
large-v1/v2/v31.5B~10 GB很慢最高精度
distil-small/en / distil-medium/en量化蒸馏版比原版快 2~6 倍英文加速(非官方完整版)

推荐起步策略:先用 tinybase 确认流程畅通,再按需换 small 或更大的模型。


二、安装准备:先装 ffmpeg

Whisper 处理音频文件时需要 ffmpeg——这是一个开源的音视频处理工具链。没有它,Whisper 读不了 MP3、WAV、FLAC 等常见格式。

macOS

brew install ffmpeg

如果你还没装 Homebrew,先去 https://brew.sh 安装。

Ubuntu / Debian

sudo apt update && sudo apt install -y ffmpeg

Windows

最方便的方式是通过 winget 安装(Windows 10/11 自带):

winget install FFmpeg.FFMpeg

如果 winget 不可用,也可以去官网 https://ffmpeg.org/download.html 下载编译好的 Windows 预编译包,解压后把 bin 目录加到系统 PATH 环境变量中。

验证安装

安装完成后在任何终端运行:

ffmpeg -version

看到版本号输出就说明装好了。


三、安装 openai-whisper

Whisper 的 PyPI 安装包名叫 openai-whisper(注意连字符,不是 whisper 单独的名字)。安装前确保你的电脑上有 Python 3.8 或以上版本

海外网络

pip install -U openai-whisper

国内镜像加速

清华镜像(速度快,优先使用):

pip install -U openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple

阿里云镜像备用:

pip install -U openai-whisper -i https://mirrors.aliyun.com/pypi/simple

两个都失败的话再切回官方源。建议先把镜像源写到 pip 配置里省得每次敲:

# 创建/编辑配置文件
mkdir -p ~/.config/pip
cat > ~/.config/pip/pip.conf << 'EOF'
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
EOF

首次安装会下载约 1~2 GB 的模型权重文件(首次运行命令时才真正下载到缓存目录),请预留足够的磁盘空间和带宽。


四、命令行转写:从音频到文字

安装完成后的命令行工具叫 whisper。最简单的用法只传两个参数:文件名–model 指定用哪个模型。

基础用法:转成 TXT

whisper meeting.mp3 --model base

这会把 meeting.mp3 里的语音识别为文字,默认输出 .txt 格式的文本文件。

强制指定语言(重要!)

虽然 Whisper 能自动检测语言,但显式告诉它说的是什么语言会显著提高准确率。比如中文音频加上 --language zh

whisper meeting.mp3 --model small --language zh

zh 就是中文的 ISO 代码。其他常用代码:en(英语)、ja(日语)、ko(韩语)。

指定输出格式

--output_format 决定输出的文件格式,可选值包括:

格式代码说明用途
txt纯文本直接阅读
vttWebVTT 字幕YouTube/B 站上传字幕
srtSRT 字幕播放器内嵌字幕
tsv制表符分隔Excel 打开
jsonJSON 完整信息程序解析,含时间戳
all以上全部一次性导出所有格式

示例:生成带时间戳的 SRT 字幕文件:

whisper meeting.mp3 --model small --language zh --output_format srt

执行后会产出 meeting.srt,里面每一行都有精确的时间戳,可以直接拖进视频编辑器做字幕。

更多实用选项

whisper meeting.mp3 --model small --language zh --device cuda --fp16

这几个参数的含义:

  • --device cuda:强制使用 NVIDIA GPU 加速(默认会自动选 CUDA 或 CPU;如果你的显卡驱动没装好,它会 fallback 到 CPU 跑,速度会慢很多)
  • --fp16:使用半精度浮点运算(需要 GPU 支持,推理速度可提升约一倍)
  • --verbose yes:打印详细的转写日志(每个片段的置信度、时间戳等),调试时有用

想看全部可用参数:

whisper --help

五、中文识别要点

Whisper 对中文的支持已经很好了,但有几个实操细节值得注意:

1. 总是加 --language zh

很多教程写 Whisper 会自动检测语言所以不用指定——确实会检测,但手动指定能把中文准确率提 2%~5%,尤其是口音较重或背景音嘈杂的情况下。养成习惯,每次都写上。

2. 模型选择很重要

根据社区测试和实际经验:

  • tiny / base:对普通话基本够用,但对方言、专业术语容易出错
  • small性价比最高,普通中文对话准确率已很不错,8GB 内存的笔记本就能跑
  • medium / large:适合对准确度要求极高的场景,但 large-v3 需要 10GB+ VRAM

3. 音频质量影响巨大

Whisper 不挑格式(MP3、WAV、M4A 都行),但采样率 16kHz 以上的单声道音频效果更好。如果录出来的声音背景噪音大,可以考虑先用 ffmpeg 降噪:

ffmpeg -i noisy.mp3 -af lowpass=3000,highpass=100 -ac 1 clean.wav

这个命令做了两件事:去掉 3000Hz 以上的高频噪音,过滤掉 100Hz 以下的低频噪音,然后转成单声道。对白类音频这个范围刚好覆盖人声频段。

4. B 站播客字幕场景

如果你有 podcast 或播客想出中文双语字幕,可以用 --task translate 把中文语音翻译成英文字幕:

whisper episode.mp3 --model small --language zh --task translate --output_format srt

结果输出的是英文字幕 SRT,适合给海外观众看。


六、faster-whisper:提速方案简介

如果你觉得标准 Whisper 太慢(尤其用 medium/large 模型的时候),有一个第三方加速方案叫 faster-whisper

它基于 CTranslate2 推理引擎,相比原版 whisper 有这些优势:

  • 速度快 4 倍:同样的模型,推理速度大约是原版的 4 倍
  • 内存占用少 50%:同样硬件能跑更大的模型
  • API 完全兼容:Python 调用方式几乎一模一样
  • 支持蒸馏模型:内置 distil-large-v3 等高效模型

安装很简单:

pip install faster-whisper

使用方式和标准版略有不同(用 Python API 调用为主):

from faster_whisper import WhisperModel

# 加载 small 模型(GPU 模式)
model = WhisperModel("small", device="cuda", compute_type="float16")

segments, info = model.transcribe("meeting.mp3", language="zh")
print(f"检测到语言:{info.language}")

for segment in segments:
    print(f"[{segment.start:.1f}s -> {segment.end:.1f}s] {segment.text}")

如果你没有 NVIDIA GPU,可以把 device="cpu"compute_type="int8",仍然会比标准版快不少。

云端替代方案提示:本地跑 Whisper 需要一点硬件门槛,如果你想零成本体验高质量中文语音转文字,也可以用 OpenAI 兼容 API(如云间中转站 https://cloudzone-api.cyou/ 提供 90+ 模型,包含 Whisper 系列,国内直连,价格仅为官方的一折左右),几行代码就调通了。后面我们会提到怎么用这种方式。


七、GPU 与否的差异

你有没有显卡,对 Whisper 的体验天差地别。

有 NVIDIA GPU 的情况

如果你有一张 RTX 3060(12GB)或更高:

模型CPU 推理耗时(基准)GPU 推理耗时(估算)速度提升
tiny~1x~10x 实时10 倍
base~1x~15x 实时15 倍
small~1x~8x 实时8 倍
medium~1x~4x 实时4 倍
large-v3~1x~2x 实时2 倍

注:“X 倍实时"表示处理 1 小时的音频大约只需 X 分钟。

关键命令:--device cuda --fp16 这两个标志缺一不可。

CPU 也能跑

没有独显怎么办?CPU 模式当然能用,只是慢一些:

  • tiny / base:CPU 基本实时,体验良好
  • small:约 2x5x 实时(1 小时音频约 1230 分钟)
  • medium / large:可能要把 1 小时音频跑到 1 小时以上

对于偶尔转一段会议纪要的场景,CPU + small 模型完全够用,不必非得搞 GPU。

Apple Silicon (M1/M2/M3)

Mac 的 M 系列芯片用了统一的内存架构,Whisper 原生支持 Metal 加速(macOS 12+),速度介于桌面 CPU 和中端 GPU 之间,体验不错。


八、进阶:批量处理文件夹

如果同一目录下有很多录音文件,可以用一个小循环一次搞定:

# 把所有 mp3 转成 srt
for f in *.mp3; do
  whisper "$f" --model small --language zh --output_format srt
done

配合前面的更快-whisper,效率更高。


九、总结 & 下一步

到这里你已经掌握了:

  • 如何安装 Whisper(ffmpeg + pip 两件事)
  • 如何用命令行做基本的语音转文字
  • 中文识别的关键技巧(语言标记、模型选择、降噪)
  • faster-whisper 提速方案
  • GPU/CPU/Apple Silicon 的性能差异

下一步你可以尝试:

  1. 自动化工作流:写个 cron 定时监控文件夹,新录音自动转文字
  2. 接 LLM 做摘要:转写出来的长文字,喂给大语言模型自动生成纪要——这需要 OpenAI 兼容的 API 接口。如果你不想自己搭服务器,OpenAI 兼容 API(如云间中转站 cloudzone-api.cyou) 是个不错的选择:90+ 模型按量计费、国内直连无需翻墙、支持 OpenAI 和 Anthropic 格式,新手注册就有优惠。
  3. Web UI:用 Streamlit 或 Gradio 给 Whisper 做个图形界面,分享给同事用

最后提醒一下:Whisper 是一个纯本地的工具,所有处理都在你的电脑上完成,不会把录音传到任何云服务——这对涉及商业机密或个人隐私的场景来说非常重要。


附:一键安装脚本

下面提供了完整的安装脚本(.sh + .ps1 双版本),覆盖了从环境检测到安装再到转写模板生成的全过程。公开源码,欢迎审查——不方便下载的同学可以直接复制下方完整源码,新建文本文档粘贴后改后缀为 .sh.ps1 运行。

也可是从 https://cleanresolver.com/scripts/install-whisper-guide.sh(.ps1)下载。


#!/usr/bin/env bash
set -u
# ============================================================
#  Whisper 本地语音转文字 一键脚本(macOS / Linux / WSL)
#  公开源码,欢迎审查 —— 不放心可先复制给 AI 判断
#  本主题本地工具无需 API Key
# ============================================================

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }
step()  { echo -e "${CYAN}[STEP]${NC} $1"; }

detect_network() {
  step "检测网络环境(国内 / 国外)..."
  if curl -fsI --max-time 5 "https://claude.ai" >/dev/null 2>&1; then
    info "可直连 claude.ai,判定为海外网络"
    echo "overseas"
  else
    warn "无法直连 claude.ai,判定为国内网络环境(将自动切换国内镜像)"
    echo "domestic"
  fi
}

install_ffmpeg_domestic() {
  # 方案1:apt(Debian/Ubuntu/WSL)
  if command -v apt-get >/dev/null 2>&1; then
    info "使用 apt 安装 ffmpeg..."
    if sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  # 方案2:dnf(Fedora/RHEL)
  if command -v dnf >/dev/null 2>&1; then
    info "使用 dnf 安装 ffmpeg..."
    if sudo dnf install -y ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  # 方案3:yum(CentOS 7 等老版本)
  if command -v yum >/dev/null 2>&1; then
    info "使用 yum 安装 ffmpeg..."
    if sudo yum install -y epel-release ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  return 1
}

install_ffmpeg_overseas() {
  if command -v apt-get >/dev/null 2>&1; then
    sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg
    return $?
  fi
  if command -v brew >/dev/null 2>&1; then
    brew install ffmpeg
    return $?
  fi
  if command -v dnf >/dev/null 2>&1; then
    sudo dnf install -y ffmpeg
    return $?
  fi
  if command -v yum >/dev/null 2>&1; then
    sudo yum install -y epel-release ffmpeg
    return $?
  fi
  return 1
}

ensure_ffmpeg() {
  step "检查 ffmpeg..."
  if command -v ffmpeg >/dev/null 2>&1; then
    info "ffmpeg 已安装:$(ffmpeg -version 2>&1 | head -1)"
    return 0
  fi
  warn "未检测到 ffmpeg,正在安装..."
  local NET="$1"
  if [ "$NET" = "domestic" ]; then
    if install_ffmpeg_domestic; then
      info "ffmpeg 安装成功"
      return 0
    fi
  else
    if install_ffmpeg_overseas; then
      info "ffmpeg 安装成功"
      return 0
    fi
  fi
  error "所有源安装 ffmpeg 均失败。"
  echo "  · Debian/Ubuntu/WSL:手动执行 sudo apt-get install ffmpeg"
  echo "  · macOS:手动执行 brew install ffmpeg"
  echo "  · Fedora/RHEL:手动执行 sudo dnf install ffmpeg"
  echo "  · CentOS:手动执行 sudo yum install epel-release ffmpeg"
  echo "  · Windows:请移步 https://ffmpeg.org/download.html 下载预编译包"
  return 1
}

check_python() {
  step "检查 Python 3..."
  local found=""
  for p in python3.11 python3.10 python3.9 python3.8 python3; do
    if "$p" --version 2>&1 | grep -qE "^Python 3\.[89]|^Python 3\.1[01]"; then
      found="$p"; break
    fi
    # catch 3.12+
    if "$p" --version 2>&1 | grep -qE "^Python 3\.[0-9][0-9]"; then
      found="$p"; break
    fi
  done
  if [ -n "$found" ]; then
    PY="$found"; info "找到 $PY$($PY --version 2>&1)"; return 0
  fi
  error "需要 Python 3.8+,未找到。请先安装:https://www.python.org/downloads/"
  return 1
}

install_whisper() {
  local net="$1"
  step "安装 openai-whisper..."

  local pypi_arg=""
  if [ "$net" = "domestic" ]; then
    pypi_arg="-i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn"
  fi

  # 主源尝试
  if eval "$PY -m pip install -U openai-whisper $pypi_arg --timeout 120" >/dev/null 2>&1; then
    info "openai-whisper 安装成功(主源)"
    return 0
  fi

  warn "主源失败,回退备用源..."

  # 备用源:阿里云
  if [ "$net" = "domestic" ]; then
    if "$PY" -m pip install -U openai-whisper \
       -i https://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com \
       --timeout 120 >/dev/null 2>&1; then
      info "openai-whisper 安装成功(阿里云镜像)"
      return 0
    fi
  fi

  # 最终回退:官方源
  if "$PY" -m pip install -U openai-whisper --timeout 120 >/dev/null 2>&1; then
    info "openai-whisper 安装成功(官方源)"
    return 0
  fi

  error "openai-whisper 安装失败。请手动尝试:"
  echo "  · 国内:pip install -U openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple"
  echo "  · 海外:pip install -U openai-whisper"
  echo "  · 如遇 torch 依赖问题,请先安装 torch:pip install torch torchaudio"
  return 1
}

write_usage_template() {
  step "生成转写使用模板..."

  cat > whisper-usage.sh << 'USAGE'
#!/usr/bin/env bash
# Whisper 转写模板(替换为你自己的文件名)
# 用法:chmod +x whisper-usage.sh && ./whisper-usage.sh your-file.mp3

TARGET="${1:-meeting.mp3}"
MODEL="${2:-small}"   # tiny | base | small | medium | large-v3
LANGUAGE="${3:-zh}"   # zh | en | ja | ko ...

echo "转写中:$TARGET(模型=$MODEL,语言=$LANGUAGE)..."
whisper "$TARGET" --model "$MODEL" --language "$LANGUAGE" --output_format all

echo ""
echo "已完成!输出文件:"
ls -lh "${TARGET%.*}".{txt,vtt,srt,tsv,json} 2>/dev/null || echo "(无输出文件,请检查上面报错)"
USAGE

  chmod +x whisper-usage.sh
  info "已生成 whisper-usage.sh(Usage: ./whisper-usage.sh <audio-file> [model] [language])"
}

main() {
  echo "============================================"
  echo "  Whisper 本地语音转文字 一键脚本"
  echo "  适用于 macOS / Linux / WSL"
  echo "============================================"
  echo ""

  local NET
  NET=$(detect_network)

  ensure_ffmpeg "$NET" || exit 1
  check_python || exit 1
  install_whisper "$NET" || exit 1

  write_usage_template

  # 验证安装
  step "验证安装..."
  if command -v whisper >/dev/null 2>&1; then
    info "Whisper 版本:$(whisper --help 2>&1 | head -1)"
  else
    warn "whisper 命令不在 PATH 中,可能需要重新打开终端"
  fi

  echo ""
  echo "============================================"
  info "全部完成!"
  echo ""
  echo "快速上手:"
  echo "  whisper your-audio.mp3 --model tiny --language zh"
  echo "  whisper your-audio.mp3 --model small --language zh --output_format srt"
  echo ""
  echo "一键转写模板:./whisper-usage.sh"
  echo ""
  echo "想省事?云端 OpenAI 兼容 API(如 https://cloudzone-api.cyou/)"
  echo "  90+ 模型、按量计费、国内直连,新手注册有优惠"
  echo "============================================"
}

main "$@"

# ============================================================
#  Whisper 本地语音转文字 一键脚本(Windows PowerShell)
#  公开源码,欢迎审查 -- 不放心可先复制给 AI 判断
#  本主题本地工具无需 API Key
# ============================================================
$ErrorActionPreference = "Stop"

function Write-Info  { Write-Host "[INFO] $args" -ForegroundColor Green }
function Write-Warn  { Write-Host "[WARN] $args" -ForegroundColor Yellow }
function Write-Err   { Write-Host "[ERROR] $args" -ForegroundColor Red }
function Write-Step  { Write-Host "[STEP] $args" -ForegroundColor Cyan }

function Detect-Network {
    Write-Step "检测网络环境(国内 / 国外)..."
    try {
        $null = Invoke-WebRequest -Uri "https://claude.ai" -Method Head -TimeoutSec 5 -UseBasicParsing
        Write-Info "可直连 claude.ai,判定为海外网络"
        return "overseas"
    } catch {
        Write-Warn "无法直连 claude.ai,判定为国内网络环境(将自动切换国内镜像)"
        return "domestic"
    }
}

function Ensure-FFmpeg {
    param([string]$Net)
    Write-Step "检查 ffmpeg..."
    if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
        $ver = & ffmpeg -version 2>&1 | Select-Object -First 1
        Write-Info "ffmpeg 已安装:$ver"
        return $true
    }

    Write-Warn "未检测到 ffmpeg,正在安装..."

    # 方式1:winget
    if (Get-Command winget -ErrorAction SilentlyContinue) {
        Write-Info "通过 winget 安装 ffmpeg..."
        try {
            winget install --id FFmpeg.FFMpeg --accept-source-agreements --accept-package-agreements --silent --disable-interactivity
            Start-Sleep -Seconds 5
            if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
                Write-Info "ffmpeg 安装成功"
                return $true
            }
        } catch {
            Write-Warn "winget 安装失败:$_"
        }
    }

    # 方式2:scoop(如果已安装)
    if (Get-Command scoop -ErrorAction SilentlyContinue) {
        Write-Info "通过 scoop 安装 ffmpeg..."
        try {
            scoop install ffmpeg
            if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
                Write-Info "ffmpeg 安装成功"
                return $true
            }
        } catch {
            Write-Warn "scoop 安装失败:$_"
        }
    }

    # 方式3: Chocolatey
    if (Get-Command choco -ErrorAction SilentlyContinue) {
        Write-Info "通过 choco 安装 ffmpeg..."
        try {
            choco install ffmpeg -y
            if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
                Write-Info "ffmpeg 安装成功"
                return $true
            }
        } catch {
            Write-Warn "choco 安装失败:$_"
        }
    }

    Write-Err "所有源安装 ffmpeg 均失败。"
    Write-Host ""
    Write-Host "  · 方式1:winget install FFmpeg.FFMpeg"
    Write-Host "  · 方式2:先装 Scoop(https://scoop.sh),再 scoop install ffmpeg"
    Write-Host "  · 方式3:前往 https://ffmpeg.org/download.html 下载预编译包,解压后将 bin 目录加入系统 PATH"
    Write-Host ""
    return $false
}

function Check-Python {
    Write-Step "检查 Python 3..."
    foreach ($pyVer in @("python3.11","python3.10","python3.9","python3.8","python3")) {
        $cmd = Get-Command $pyVer -ErrorAction SilentlyContinue
        if ($cmd) {
            $verStr = &$pyVer --Version 2>&1
            if ($verStr -match 'Python 3\.') {
                $script:PY = $pyVer
                Write-Info "找到 $pyVer$verStr"
                return $true
            }
        }
    }
    Write-Err "需要 Python 3.8+,未找到。"
    Write-Host "  前往 https://www.python.org/downloads/ 下载安装,注意勾选「Add Python to PATH」"
    return $false
}

function Install-Whisper {
    param([string]$Net)
    Write-Step "安装 openai-whisper..."

    $pypiUrl = ""
    $trustedHost = ""
    if ($Net -eq "domestic") {
        $pypiUrl = "-i https://pypi.tuna.tsinghua.edu.cn/simple"
        $trustedHost = "--trusted-host pypi.tuna.tsinghua.edu.cn"
    }

    $mainCmd = "$script:PY -m pip install -U openai-whisper $pypiUrl $trustedHost --timeout 120"
    try {
        Invoke-Expression $mainCmd 2>$null | Out-Null
        Write-Info "openai-whisper 安装成功(主源)"
        return $true
    } catch {
        Write-Warn "主源安装失败:$_"
    }

    # 备用源:阿里云
    if ($Net -eq "domestic") {
        $altCmd = "$script:PY -m pip install -U openai-whisper -i https://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com --timeout 120"
        try {
            Invoke-Expression $altCmd 2>$null | Out-Null
            Write-Info "openai-whisper 安装成功(阿里云镜像)"
            return $true
        } catch {
            Write-Warn "备用源安装失败:$_"
        }
    }

    # 最终回退:官方源
    try {
        $offCmd = "$script:PY -m pip install -U openai-whisper --timeout 120"
        Invoke-Expression $offCmd 2>$null | Out-Null
        Write-Info "openai-whisper 安装成功(官方源)"
        return $true
    } catch {
        Write-Err "openai-whisper 安装失败。请手动尝试:"
        Write-Host "  · 国内:pip install -U openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple"
        Write-Host "  · 海外:pip install -U openai-whisper"
        Write-Host "  · 如遇 torch 依赖问题,请先安装 torch:pip install torch torchaudio"
        return $false
    }
}

function Write-Usage-Template {
    Write-Step "生成转写使用模板..."

    $templatePath = Join-Path (Get-Location).Path "whisper-usage.bat"
    $batContent = @"
@echo off
REM Whisper 转写批处理模板
REM 用法:whisper-usage.bat audio-file.mp3 [model] [language]
set TARGET=%~1
if "%TARGET%"=="" set TARGET=meeting.mp3
set MODEL=%~2
if "%MODEL%"=="" set MODEL=small
set LANGUAGE=%~3
if "%LANGUAGE%"=="" set LANGUAGE=zh

echo 转写中:%TARGET%(模型=%MODEL%%,语言=%LANGUAGE%)...
whisper "%TARGET%" --model %MODEL% --language %LANGUAGE% --output_format all

echo.
echo 已完成!输出文件:
dir /b "%TARGET%.*" | findstr "\.txt \|\.vtt \|\.srt \|\.tsv \|\.json" 2>nul || echo (无输出文件,请检查上面报错)
"@
    Set-Content -Path $templatePath -Value $batContent -Encoding UTF8
    Write-Info "已生成 whisper-usage.bat"
}

# ========== 主流程 ==========
Write-Host "============================================"
Write-Host "  Whisper 本地语音转文字 一键脚本"
Write-Host "  适用于 Windows (PowerShell)"
Write-Host "============================================"
Write-Host ""

$net = Detect-Network

if (-not (Ensure-FFmpeg -Net $net)) {
    Write-Err "ffmpeg 安装失败,脚本终止。"
    exit 1
}

if (-not (Check-Python)) {
    exit 1
}

if (-not (Install-Whisper -Net $net)) {
    Write-Err "Whisper 安装失败,脚本终止。"
    exit 1
}

Write-Usage-Template

# 验证
Write-Step "验证安装..."
try {
    $whisperHelp = whisper --help 2>&1 | Select-Object -First 1
    Write-Info "Whisper 命令可用"
} catch {
    Write-Warn "whisper 命令不在 PATH 中,可能需要重开终端窗口"
}

Write-Host ""
Write-Host "============================================"
Write-Info "全部完成!"
Write-Host ""
Write-Host "快速上手:"
Write-Host "  whisper your-audio.mp3 --model tiny --language zh"
Write-Host "  whisper your-audio.mp3 --model small --language zh --output_format srt"
Write-Host ""
Write-Host "一键转写模板:.\whisper-usage.bat"
Write-Host ""
Write-Host "想省事?云端 OpenAI 兼容 API(如 https://cloudzone-api.cyou/)"
Write-Host "  90+ 模型、按量计费、国内直连,新手注册有优惠"
Write-Host "============================================"

声明:本文脚本公开源码,欢迎复制给任何 AI 审查后再运行。一切安装操作你拥有完全的控制权,可随时查看脚本内容确认其行为。