import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import subprocess
import os
# subprocess这个库在python2.4以上版本自带
# tkinter库这个呢没有的话请自行安装
# 创建文本转语音函数
def text_to_speech(text, output_file, voice_name):
# 确保文件路径有效
if not os.path.exists(os.path.dirname(output_file)):
result_label.config(text="错误:保存路径不存在")
return
# 检查文件是否已经存在,避免覆盖
if os.path.exists(output_file):
result_label.config(text="错误:文件已存在,请选择不同的文件名")
return
# 清理文本中的换行符
cleaned_text = text.replace("\n", " ").replace("\r", "") # 将换行符替换为空格或空字符
# 调用 edge-tts 生成语音
command = f"edge-tts --text "{cleaned_text}" --voice {voice_name} --write-media {output_file}"
# print(command)
try:
subprocess.run(command, shell=True, check=True)
result_label.config(text=f"语音文件已生成:{output_file}")
except subprocess.CalledProcessError as e:
result_label.config(text=f"生成语音时发生错误: {e}")
# 创建生成语音的回调函数
def generate_speech():
text = text_input.get("1.0", "end-1c") # 获取文本框中的文本
if text.strip(): # 确保文本框不为空
# 让用户选择保存路径
output_file = filedialog.asksaveasfilename(defaultextension=".mp3", filetypes=[("MP3 files", "*.mp3")])
if output_file:
# 获取用户选择的语音源
selected_voice = voice_combobox.get()
# 映射用户选择的语音描述到正确的语音名称
voice_mapping = {
"英语 - Aria (美国)女": "en-US-AriaNeural",
"英语 - Brian (美国)男": "en-US-BrianNeural",
"英语 - Ryan (英国)男": "en-GB-RyanNeural",
"英语 - Sonia (英国)女": "en-GB-SoniaNeural",
"中文 - Xiaoxiao (普通话)女": "zh-CN-XiaoxiaoNeural",
"中文 - HiuGaai (粤语)女": "zh-HK-HiuGaaiNeural",
"中文 - 陕西小妮 (普通话)女": "zh-CN-shaanxi-XiaoniNeural",
"韩语 - SeoYeon (韩国)女": "ko-KR-SunHiNeural",
"俄语 - Svetlana (俄国)女": "ru-RU-SvetlanaNeural",
"日语 - Nanami (日本)女": "ja-JP-NanamiNeural"
}
voice_name = voice_mapping.get(selected_voice, "en-US-AriaNeural") # 默认使用英文语音
text_to_speech(text, output_file, voice_name)
else:
result_label.config(text="未选择文件路径")
else:
result_label.config(text="请输入文本")
# 创建窗口
root = tk.Tk()
root.title("文本转语音生成器")
# 设置窗口大小
root.geometry("420x320")
# 延迟弹出更新信息框,避免阻塞主界面
root.after(500, lambda: messagebox.showinfo("更新信息", "修复了长文本中不能含有换行符的问题!\n加入了韩、日、俄语音库\n\n注意现在还没法检测输入的文本语言,\n是否与语音库匹配会报错!\n勉强能用,语音别选错了!"))
# 创建文本框
text_input = tk.Text(root, height=8, width=30)
text_input.pack(pady=10)
# 创建选择语音的下拉框
voice_label = tk.Label(root, text="选择语音:")
voice_label.pack()
# 增加中文和英文的语音选择
voice_display = [
"英语 - Aria (美国)女", "英语 - Brian (美国)男", "英语 - Ryan (英国)男",
"英语 - Sonia (英国)女", "中文 - Xiaoxiao (普通话)女", "中文 - HiuGaai (粤语)女",
"中文 - 陕西小妮 (普通话)女", "韩语 - SeoYeon (韩国)女", "俄语 - Svetlana (俄国)女",
"日语 - Nanami (日本)女"
]
voice_combobox = ttk.Combobox(root, values=voice_display, state="readonly")
voice_combobox.set(voice_display[0]) # 默认选择第一个语音
voice_combobox.pack(pady=5)
# 创建生成语音的按钮
generate_button = tk.Button(root, text="生成语音", command=generate_speech)
generate_button.pack(pady=10)
# 显示结果的标签
result_label = tk.Label(root, text="")
result_label.pack()
# 运行主循环
root.mainloop()