本文目录导读:

- 使用 pyttsx3(离线方案)
- 使用 gTTS(Google在线方案)
- 使用百度语音合成API(在线方案)
- 使用Edge TTS(微软在线方案)
- 使用 OpenAI TTS(需要API密钥)
- 完整示例:带GUI界面的TTS工具
- 各方案对比
- 安装依赖
我来为您介绍几种Python文本转语音的实现方法:
使用 pyttsx3(离线方案)
import pyttsx3
# 初始化
engine = pyttsx3.init()
# 设置属性
engine.setProperty('rate', 150) # 语速(默认200)
engine.setProperty('volume', 0.9) # 音量(0-1)
# 获取语音列表
voices = engine.getProperty('voices')
# 设置中文语音(Windows)
for voice in voices:
if 'chinese' in voice.name.lower() or 'zh' in voice.id.lower():
engine.setProperty('voice', voice.id)
break
# 文字转语音并保存到文件
text = "你好,欢迎使用Python文字转语音功能"
engine.save_to_file(text, 'output.mp3')
engine.runAndWait()
# 直接播放
engine.say(text)
engine.runAndWait()
使用 gTTS(Google在线方案)
# 安装:pip install gtts
from gtts import gTTS
import os
def text_to_speech_gtts(text, language='zh-CN', filename='output.mp3'):
"""
使用Google TTS进行文字转语音
"""
try:
tts = gTTS(text=text, lang=language, slow=False)
tts.save(filename)
print(f"音频已保存为: {filename}")
# 播放音频(可选)
os.system(f"start {filename}") # Windows
# os.system(f"afplay {filename}") # Mac
# os.system(f"mpg321 {filename}") # Linux
except Exception as e:
print(f"转换失败: {e}")
# 使用示例
text = "今天天气真好,适合出去散步"
text_to_speech_gtts(text, 'zh-CN', 'weather.mp3')
使用百度语音合成API(在线方案)
# 安装:pip install baidu-aip
from aip import AipSpeech
""" 你的 APPID AK SK """
APP_ID = '你的APP_ID'
API_KEY = '你的API_KEY'
SECRET_KEY = '你的SECRET_KEY'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def text_to_speech_baidu(text, file_path='output.mp3'):
"""
使用百度语音合成
"""
result = client.synthesis(text, 'zh', 1, {
'vol': 5, # 音量
'spd': 4, # 语速
'pit': 5, # 音调
'per': 4 # 发音人:0女声,1男声,3男情,4女情
})
if not isinstance(result, dict):
with open(file_path, 'wb') as f:
f.write(result)
print(f"音频已保存为: {file_path}")
else:
print(f"合成失败: {result}")
# 使用示例
text = "Python语音合成功能测试"
text_to_speech_baidu(text, 'baidu_output.mp3')
使用Edge TTS(微软在线方案)
# 安装:pip install edge-tts
import edge_tts
import asyncio
async def text_to_speech_edge(text, voice='zh-CN-XiaoxiaoNeural', file_path='output.mp3'):
"""
使用微软Edge TTS
中文语音可选:zh-CN-XiaoxiaoNeural(女), zh-CN-YunxiNeural(男)
"""
communicate = edge_tts.Communicate(text, voice)
await communicate.save(file_path)
print(f"音频已保存为: {file_path}")
# 使用示例
text = "这是一个使用微软语音合成的测试案例"
asyncio.run(text_to_speech_edge(text))
# 获取可用语音列表
async def list_voices():
voices = await edge_tts.list_voices()
for voice in voices:
if 'Chinese' in voice['Locale']:
print(f"{voice['Name']}: {voice['ShortName']}")
# asyncio.run(list_voices())
使用 OpenAI TTS(需要API密钥)
# 安装:pip install openai
from openai import OpenAI
import os
def text_to_speech_openai(text, file_path='output.mp3', voice='alloy'):
"""
使用OpenAI TTS
voice参数: alloy, echo, fable, onyx, nova, shimmer
"""
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
response = client.audio.speech.create(
model="tts-1",
voice=voice,
input=text
)
response.stream_to_file(file_path)
print(f"音频已保存为: {file_path}")
# 使用示例
text = "Hello, this is a test of OpenAI's text to speech system."
text_to_speech_openai(text, 'openai_output.mp3', 'alloy')
完整示例:带GUI界面的TTS工具
import tkinter as tk
from tkinter import ttk, scrolledtext
import pyttsx3
import threading
class TTSApp:
def __init__(self, root):
self.root = root
self.root.title("文字转语音工具")
self.root.geometry("500x400")
# 初始化TTS引擎
self.engine = pyttsx3.init()
self.setup_ui()
def setup_ui(self):
# 文字输入
tk.Label(self.root, text="请输入要转换的文字:").pack(pady=10)
self.text_input = scrolledtext.ScrolledText(
self.root, width=50, height=10
)
self.text_input.pack(padx=10, pady=5)
# 设置框架
control_frame = tk.Frame(self.root)
control_frame.pack(pady=10)
# 语速设置
tk.Label(control_frame, text="语速:").grid(row=0, column=0)
self.rate_var = tk.IntVar(value=150)
rate_scale = tk.Scale(
control_frame, from_=50, to=300,
orient=tk.HORIZONTAL, variable=self.rate_var
)
rate_scale.grid(row=0, column=1)
# 按钮
btn_frame = tk.Frame(self.root)
btn_frame.pack(pady=10)
tk.Button(
btn_frame, text="播放",
command=self.play_text, width=10
).pack(side=tk.LEFT, padx=5)
tk.Button(
btn_frame, text="保存到文件",
command=self.save_to_file, width=10
).pack(side=tk.LEFT, padx=5)
tk.Button(
btn_frame, text="清空",
command=self.clear_text, width=10
).pack(side=tk.LEFT, padx=5)
def play_text(self):
text = self.text_input.get("1.0", tk.END).strip()
if text:
def play():
self.engine.setProperty('rate', self.rate_var.get())
self.engine.say(text)
self.engine.runAndWait()
threading.Thread(target=play, daemon=True).start()
def save_to_file(self):
text = self.text_input.get("1.0", tk.END).strip()
if text:
from tkinter import filedialog
filename = filedialog.asksaveasfilename(
defaultextension=".mp3",
filetypes=[("MP3文件", "*.mp3"), ("所有文件", "*.*")]
)
if filename:
self.engine.setProperty('rate', self.rate_var.get())
self.engine.save_to_file(text, filename)
self.engine.runAndWait()
tk.messagebox.showinfo("成功", f"音频已保存为:{filename}")
def clear_text(self):
self.text_input.delete("1.0", tk.END)
# 运行GUI应用
if __name__ == "__main__":
root = tk.Tk()
app = TTSApp(root)
root.mainloop()
各方案对比
| 方案 | 优点 | 缺点 |
|---|---|---|
| pyttsx3 | 离线可用,支持中文 | 语音质量一般 |
| gTTS | 免费,语音自然 | 需要网络,较慢 |
| 百度TTS | 中文支持好,多种音色 | 需要API密钥 |
| Edge TTS | 免费,语音质量高 | 需要网络 |
| OpenAI | 语音质量顶级 | 付费,需要API密钥 |
安装依赖
# 基础方案 pip install pyttsx3 # 在线方案 pip install gtts pip install baidu-aip pip install edge-tts pip install openai
选择哪个方案取决于您的具体需求:是否需要离线、语音质量要求、预算等,建议先使用pyttsx3进行测试,如果需要更好的语音质量,可以尝试Edge TTS或gTTS。