选择合适的TTS工具

当前主流的TTS(Text-to-Speech)工具包括Google Cloud Text-to-Speech、Amazon Polly、Microsoft Azure Cognitive Services等云服务,以及开源的TTS库如Coqui TTS、Festival等。云服务通常提供更自然的声音,但需要API密钥;开源工具可本地部署,灵活性更高。

安装必要的库

以Python为例,使用Google TTS需要安装google-cloud-texttospeech库:

pip install google-cloud-texttospeech

若选择开源方案如Coqui TTS:

pip install TTS

配置API密钥(云服务)

对于Google TTS,需在Google Cloud控制台创建项目并启用Text-to-Speech API,下载JSON格式的服务账户密钥,设置环境变量:

export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/service-account-key.json"

生成语音的基本代码示例

使用Google TTS合成语音的Python代码:

from google.cloud import texttospeech

client = texttospeech.TextToSpeechClient()
input_text = texttospeech.SynthesisInput(text="这是要合成的语音内容")
voice = texttospeech.VoiceSelectionParams(
    language_code="zh-CN",
    name="zh-CN-Wavenet-A"
)
audio_config = texttospeech.AudioConfig(
    audio_encoding=texttospeech.AudioEncoding.MP3
)
response = client.synthesize_speech(
    input=input_text, voice=voice, audio_config=audio_config
)
with open("output.mp3", "wb") as out:
    out.write(response.audio_content)

自定义语音参数

调整语音参数可改变输出效果:

  • language_code:设置语言(如en-USzh-CN)。
  • voice.name:选择特定音色(如en-US-Wavenet-D为低沉男声)。
  • audio_config:设置编码格式(如LINEAR16为WAV格式)。

使用开源工具(Coqui TTS)

以下示例加载预训练模型并生成语音:

from TTS.api import TTS

tts = TTS(model_name="tts_models/zh-CN/baker/tacotron2-DDC-GST")
tts.tts_to_file(text="这是开源TTS合成的语音", file_path="output.wav")

批量处理文本文件

通过循环处理多段文本,生成系列语音文件:

with open("texts.txt", "r") as f:
    for i, line in enumerate(f):
        response = client.synthesize_speech(
            input=texttospeech.SynthesisInput(text=line.strip()),
            voice=voice,
            audio_config=audio_config
        )
        with open(f"output_{i}.mp3", "wb") as out:
            out.write(response.audio_content)

调整语音风格(如情感语调)

部分高级API支持情感参数。例如Microsoft Azure TTS可通过style设置:

voice = texttospeech.VoiceSelectionParams(
    language_code="zh-CN",
    name="zh-CN-YunxiNeural",
    style="cheerful"  # 可选"sad", "angry"等
)

注意事项

  • 云服务可能有免费额度限制,超出后会产生费用。
  • 开源模型需注意训练数据授权问题,避免商用侵权。
  • 中文合成建议选择支持zh-CNzh-TW的模型,部分模型需单独下载语音权重。

更多推荐