雲端語音合成 API 會將應用程式的文字傳送至外部伺服器。Piper 是僅在本機執行的 TTS(文字轉語音)引擎,使用輕量神經網路將文字合成為語音。我安裝了 Piper,並在停用網路的情況下測試語音合成。
Piper 使用輕量的神經網路語音合成模型,設計上可在 Raspberry Pi 等小型裝置上以快於即時播放的速度執行。Piper 的原始碼採用 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
程式產生了 4.47 秒的語音,耗時 1.51 秒。1.51 秒的合成時間短於 4.47 秒的音訊長度,因此 Piper 達到了以快於即時播放的速度執行的設計目標。我載入產生的檔案,確認格式為 RIFF/WAVE, 16bit PCM, mono, 22050Hz,並確認檔案沒有損毀。本次記錄未評估語音的可理解度。
合成語音,無須將文字傳送至公司外部
應用程式可能會將要轉換為語音的文字傳送至外部服務。Piper 將模型保留在您的系統上,因此應用程式可以合成語音,無須將文字傳送至公司外部。我確認 Piper 的執行速度快於即時播放,因此需要即時效能的應用程式可以考慮使用它。
來源
*1 Piper (GitHub), https://github.com/rhasspy/piper, MIT License