← 研究笔记
不依赖云端合成语音:运行 Piper

不依赖云端合成语音:运行 Piper

记录在禁用网络的情况下运行 Piper(一款本地神经文本转语音引擎)的过程。它生成音频文件的速度快于实时播放速度。

本文涉及的仓库

rhasspy/piper

A fast, local neural text to speech system

11.2k C++ MIT License

云端语音合成 API 会把应用中的文本发送到外部服务器。Piper 是一款仅在本地运行的 TTS(text-to-speech,文本转语音)引擎,使用轻量级神经网络将文本合成为语音。我安装了 Piper,并在禁用网络的情况下测试了语音合成。

Piper 使用轻量级神经语音合成模型,专为在 Raspberry Pi 等小型设备上以快于实时的速度运行而设计。其源代码采用 MIT 许可证(*1)。

1. 安装 Piper 并下载语音模型

在网络访问可用时,在构建过程中下载英语语音模型(en_US-lessac-medium)。

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'piper-tts==1.4.2'
RUN python -m piper.download_voices en_US-lessac-medium --data-dir /opt/piper-voices
WORKDIR /work
podman build -t piper-sandbox .

2. 在禁用网络的情况下运行语音合成

import time
import wave
from piper import PiperVoice

voice = PiperVoice.load(
    "/opt/piper-voices/en_US-lessac-medium.onnx",
    config_path="/opt/piper-voices/en_US-lessac-medium.onnx.json",
)

text = "Open source software lets anyone read, modify, and redistribute the code."

t0 = time.time()
with wave.open("/work/output.wav", "wb") as wav_file:
    voice.synthesize_wav(text, wav_file)
elapsed = time.time() - t0

with wave.open("/work/output.wav", "rb") as wav_file:
    duration = wav_file.getnframes() / wav_file.getframerate()

print(f"synthesis time: {elapsed:.2f}s")
print(f"audio duration: {duration:.2f}s")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work piper-sandbox \
  python tts_demo.py

-v 选项会让指定目录在容器内可供读取和写入。请在一个专门用于本次实验的空目录中运行该命令。

命令返回了以下结果:

synthesis time: 1.51s
audio duration: 4.47s
sample rate: 22050 Hz

程序在 1.51 秒内生成了时长为 4.47 秒的语音。语音合成耗时 1.51 秒,短于 4.47 秒的音频时长,因此 Piper 达成了以快于实时的速度运行这一设计目标。我加载了生成的文件,确认其格式为 RIFF/WAVE, 16bit PCM, mono, 22050Hz,未发现文件损坏。本次记录未评估语音的可懂度。

合成语音时不向公司外部发送文本

应用可以将要转换为语音的文本发送给外部服务。Piper 将模型保存在你的系统中,因此应用无需把文本发送到公司外部即可合成语音。我确认 Piper 的运行速度快于实时,这使它适合需要实时性能的应用。

来源

*1 Piper (GitHub), https://github.com/rhasspy/piper, MIT License