在 Google Colab 上自托管文本转语音应用

发布: (2025年12月19日 GMT+8 18:37)
8 分钟阅读
原文: Dev.to

I’m happy to translate the article for you, but I need the full text you’d like translated. Could you please paste the content (excluding the source line you already provided) here? Once I have the text, I’ll translate it into Simplified Chinese while preserving all formatting, markdown, and code blocks.

Introduction

文本转语音已经悄然从机械化的演示进化为听起来自然且富有表现力的声音。问题在于,高质量的语音通常伴随使用限制或按字符计费。即使在本地运行现代模型,也往往需要强大的 GPU,难度不小。一个实用的折中方案是使用免费云计算并自行托管应用。

在本文中,我们将使用 Google ColabKokoro TTS 模型、配合 Gradio 的简洁界面,以及通过 Pinggy 提供的公网访问,构建一个完整的文本转语音 Web 应用。所有内容都在 Colab 笔记本中运行,并在会话存活期间保持活跃。

为什么在 Colab 上运行文本转语音

  • 大多数商业 TTS 平台按字符数或音频时长计费。这对小项目来说还算可行,但在实验或生成大量音频时很快就会受到限制。
  • Colab 提供免费使用 Tesla T4 GPU,对轻量级语音模型来说绰绰有余。虽然 Kokoro 也可以在 CPU 上运行,但 GPU 加速可以让生成速度更快、更流畅,尤其是处理较长文本时。
  • Colab 笔记本默认不对外公开。这时 Pinggy 就派上用场了。它会创建一个安全隧道,并用公开的 URL 暴露你的本地 Web 应用。这样,你可以在笔记本中编写代码,运行 Web 应用,并通过任意浏览器访问它。

开始使用环境

  1. colab.google.com 打开一个新笔记本。
  2. Runtime 菜单中,更改运行时类型并启用 GPU(如果有 T4 可选,请选择 T4)。

安装 Pinggy

在启动 Web 应用之前,需要先激活隧道。

!pip install pinggy

启动隧道

import pinggy

tunnel = pinggy.start_tunnel(
    forwardto="localhost:5000"
)

print("Public URLs:", tunnel.urls)

保留打印出的 URL —— 稍后打开应用时需要使用它。

安装文本转语音依赖

!pip install kokoro-onnx gradio soundfile torch numpy
  • kokoro‑onnx – 处理语音合成。
  • gradio – 构建网页界面。
  • soundfile – 保存音频输出。

Understanding Kokoro TTS

  • Kokoro ONNX 基于 Kokoro 82M 模型,并针对高效推理进行了优化。
  • 该模型体积相对较小,却能生成自然清晰的语音。
  • 它支持多种语言(英语、日语、德语、法语、西班牙语、意大利语、中文、韩语、葡萄牙语、俄语)和多种声线风格(男性 & 女性)。
  • 由于轻量化,它能够轻松适配 Colab 的内存限制,并在免费 GPU 版上可靠运行。

核心文本转语音逻辑

import soundfile as sf
import urllib.request
import tempfile
import uuid
import os
from kokoro_onnx import Kokoro

# ----------------------------------------------------------------------
# Model URLs
# ----------------------------------------------------------------------
MODEL_URL = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/"
model_path = "kokoro-v1.0.onnx"
voices_bin_path = "voices-v1.0.bin"

# ----------------------------------------------------------------------
# Download if missing
# ----------------------------------------------------------------------
if not os.path.exists(model_path):
    urllib.request.urlretrieve(MODEL_URL + "kokoro-v1.0.onnx", model_path)

if not os.path.exists(voices_bin_path):
    urllib.request.urlretrieve(MODEL_URL + "voices-v1.0.bin", voices_bin_path)

# ----------------------------------------------------------------------
# Load model
# ----------------------------------------------------------------------
kokoro = Kokoro(model_path, voices_bin_path)

voice_options = list(kokoro.voices.keys())
VOICE_LABELS = {v.replace("_", " ").title(): v for v in voice_options}

LANG_LABELS = {
    "English US": "en-us",
    "English UK": "en-gb",
    "Japanese": "ja-jp",
    "Chinese": "zh-cn",
    "German": "de-de",
    "Spanish": "es-es",
    "French": "fr-fr",
    "Italian": "it-it",
    "Korean": "ko-kr",
    "Portuguese": "pt-br",
    "Russian": "ru-ru",
}

def tts_generate(text, voice_label, speed, language):
    """Generate speech from text."""
    if not text.strip():
        return None, "Please enter text"

    voice_id = VOICE_LABELS[voice_label]
    lang_code = LANG_LABELS[language]

    samples, sr = kokoro.create(
        text=text,
        voice=voice_id,
        speed=float(speed),
        lang=lang_code
    )

    filename = f"tts_{uuid.uuid4().hex[:8]}.wav"
    path = os.path.join(tempfile.gettempdir(), filename)
    sf.write(path, samples, sr)

    return path, "Audio generated"

该函数接受 textvoicespeedlanguage,然后返回一个可播放的音频文件。

使用 Gradio 构建网页界面

Gradio 让我们只用极少的代码就能将 TTS 功能转化为可用的网页应用。

import gradio as gr

def build_ui():
    with gr.Blocks(title="Text to Speech AI") as app:
        gr.Markdown("### Text to Speech AI")

        # --------------------------------------------------------------
        # Input components
        # --------------------------------------------------------------
        text_input = gr.Textbox(
            label="Text",
            placeholder="Enter text here",
            lines=4
        )

        with gr.Row():
            voice_dropdown = gr.Dropdown(
                label="Voice",
                choices=list(VOICE_LABELS.keys()),
                value=list(VOICE_LABELS.keys())[0]
            )
            language_dropdown = gr.Dropdown(
                label="Language",
                choices=list(LANG_LABELS.keys()),
                value="English US"
            )

        speed_slider = gr.Slider(
            minimum=0.5,
            maximum=2.0,
            value=1.0,
            step=0.1,
            label="Speed"
        )

        generate_btn = gr.Button("Generate Speech")

        # --------------------------------------------------------------
        # Output components
        # --------------------------------------------------------------
        audio_output = gr.Audio(label="Output")
        status_output = gr.Markdown()

        # --------------------------------------------------------------
        # Interaction
        # --------------------------------------------------------------
        generate_btn.click(
            fn=tts_generate,
            inputs=[text_input, voice_dropdown, speed_slider, language_dropdown],
            outputs=[audio_output, status_output]
        )

    return app

# Launch the interface
ui = build_ui()
ui.launch(server_name="0.0.0.0", server_port=5000, share=False)

运行笔记本将会:

  1. 启动一个 Pinggy 隧道(见前文)。
  2. localhost:5000 上启动 Gradio 界面。
  3. 公开 Pinggy 提供的 URL,使任何拥有链接的人都能使用 TTS 应用。

最后说明

  • 保持 Colab 会话活跃(例如,定期运行一个单元格)以维持隧道。
  • 如果需要更长的音频或更高的吞吐量,考虑升级到付费的 Colab 方案或专用 GPU 实例。
  • 欢迎尝试不同的声音、语言和速度设置,以找到最适合您项目的方案。

Code

inputs = [text_input, voice_dropdown, speed_slider, language_dropdown]
outputs = [audio_output, status_output]

return app

app = build_ui()
app.launch(server_name="0.0.0.0", server_port=5000, share=False)

全屏控制

  • 进入全屏模式
  • 退出全屏模式

一旦此单元格运行,应用将在笔记本内部的 5000 端口开始监听。

从浏览器访问应用

打开之前打印的 Pinggy URL。您应该会看到文本转语音界面。

  1. 输入一些文本。
  2. 选择语音和语言。
  3. 如有需要,调整速度。
  4. 生成音频。

输出可以直接播放,也可以下载为 WAV 文件。

语音和语言提示

  • 为了获得最自然的效果,请将语音前缀与文本语言匹配。
    • 英语语音 → 英文文本
    • 日语语音 → 日文文本
    • …以此类推。
  • 速度控制对朗读很有帮助;稍慢一点的语速通常能让长段落更清晰。

Performance Notes

  • 在免费 T4 GPU 上,短句几乎瞬间生成。
  • 较长的段落需要几秒钟。
  • 加载模型后第一次请求可能会感觉较慢,但后续生成会更快。
  • Colab 会话在长时间不活动后可能会断开,因此 在关闭笔记本前下载重要的音频文件

结论

在 Google Colab 上自行托管文本转语音系统,是一种实用的方式,可在不受使用限制或基础设施搭建困扰的情况下,探索高质量语音合成。

  • Kokoro 在模型大小与音频质量之间提供了良好的平衡。
  • Gradio 让界面保持简洁。
  • Pinggy 弥合了私有笔记本与公共访问之间的鸿沟。

该方案非常适合学习、原型设计、辅助工具或内容创作工作流,在这些场景中灵活性比商业化的精致平台更为重要。

References

Back to Blog

相关文章

阅读更多 »