Files
ai-short-video-generator-20…/core/tts.py
T

34 lines
909 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""语音合成模块(pyttsx3 离线 TTS)"""
import os
import pyttsx3
def text_to_speech(text: str, out_path: str, rate: int = 160) -> str:
"""将文本合成为音频文件。
Args:
text: 待合成文本
out_path: 输出音频路径(如 output/audio/1.mp3)
rate: 语速
Returns:
str: 输出文件路径
"""
os.makedirs(os.path.dirname(out_path), exist_ok=True)
engine = pyttsx3.init()
engine.setProperty("rate", rate)
# 选择第一个可用语音(不同系统可能不同)
voices = engine.getProperty("voices")
if voices:
engine.setProperty("voice", voices[0].id)
engine.save_to_file(text, out_path)
engine.runAndWait()
engine.stop()
return out_path
if __name__ == "__main__":
print(text_to_speech("你好,这是一段测试语音。", "output/audio/test.mp3"))