鱼C论坛

 找回密码
 立即注册
查看: 245|回复: 1

[技术交流] 大家看下这个文本转语音的小程序怎么样?

[复制链接]
发表于 2025-2-10 15:01:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import tkinter as tk
  2. from tkinter import filedialog, ttk, messagebox
  3. import subprocess
  4. import os

  5. # subprocess这个库在python2.4以上版本自带
  6. # tkinter库这个呢没有的话请自行安装

  7. # 创建文本转语音函数
  8. def text_to_speech(text, output_file, voice_name):
  9.     # 确保文件路径有效
  10.     if not os.path.exists(os.path.dirname(output_file)):
  11.         result_label.config(text="错误:保存路径不存在")
  12.         return
  13.    
  14.     # 检查文件是否已经存在,避免覆盖
  15.     if os.path.exists(output_file):
  16.         result_label.config(text="错误:文件已存在,请选择不同的文件名")
  17.         return
  18.    
  19.     # 清理文本中的换行符
  20.     cleaned_text = text.replace("\n", " ").replace("\r", "")  # 将换行符替换为空格或空字符
  21.    
  22.     # 调用 edge-tts 生成语音
  23.     command = f"edge-tts --text "{cleaned_text}" --voice {voice_name} --write-media {output_file}"
  24.     # print(command)
  25.     try:
  26.         subprocess.run(command, shell=True, check=True)
  27.         result_label.config(text=f"语音文件已生成:{output_file}")
  28.     except subprocess.CalledProcessError as e:
  29.         result_label.config(text=f"生成语音时发生错误: {e}")

  30. # 创建生成语音的回调函数
  31. def generate_speech():
  32.     text = text_input.get("1.0", "end-1c")  # 获取文本框中的文本
  33.     if text.strip():  # 确保文本框不为空
  34.         # 让用户选择保存路径
  35.         output_file = filedialog.asksaveasfilename(defaultextension=".mp3", filetypes=[("MP3 files", "*.mp3")])
  36.         if output_file:
  37.             # 获取用户选择的语音源
  38.             selected_voice = voice_combobox.get()
  39.             # 映射用户选择的语音描述到正确的语音名称
  40.             voice_mapping = {
  41.                 "英语 - Aria (美国)女": "en-US-AriaNeural",
  42.                 "英语 - Brian (美国)男": "en-US-BrianNeural",
  43.                 "英语 - Ryan (英国)男": "en-GB-RyanNeural",
  44.                 "英语 - Sonia (英国)女": "en-GB-SoniaNeural",
  45.                 "中文 - Xiaoxiao (普通话)女": "zh-CN-XiaoxiaoNeural",
  46.                 "中文 - HiuGaai (粤语)女": "zh-HK-HiuGaaiNeural",
  47.                 "中文 - 陕西小妮 (普通话)女": "zh-CN-shaanxi-XiaoniNeural",
  48.                 "韩语 - SeoYeon (韩国)女": "ko-KR-SunHiNeural",
  49.                 "俄语 - Svetlana (俄国)女": "ru-RU-SvetlanaNeural",
  50.                 "日语 - Nanami (日本)女": "ja-JP-NanamiNeural"
  51.             }
  52.             voice_name = voice_mapping.get(selected_voice, "en-US-AriaNeural")  # 默认使用英文语音
  53.             text_to_speech(text, output_file, voice_name)
  54.         else:
  55.             result_label.config(text="未选择文件路径")
  56.     else:
  57.         result_label.config(text="请输入文本")

  58. # 创建窗口
  59. root = tk.Tk()
  60. root.title("文本转语音生成器")

  61. # 设置窗口大小
  62. root.geometry("420x320")

  63. # 延迟弹出更新信息框,避免阻塞主界面
  64. root.after(500, lambda: messagebox.showinfo("更新信息", "修复了长文本中不能含有换行符的问题!\n加入了韩、日、俄语音库\n\n注意现在还没法检测输入的文本语言,\n是否与语音库匹配会报错!\n勉强能用,语音别选错了!"))

  65. # 创建文本框
  66. text_input = tk.Text(root, height=8, width=30)
  67. text_input.pack(pady=10)

  68. # 创建选择语音的下拉框
  69. voice_label = tk.Label(root, text="选择语音:")
  70. voice_label.pack()

  71. # 增加中文和英文的语音选择
  72. voice_display = [
  73.     "英语 - Aria (美国)女", "英语 - Brian (美国)男", "英语 - Ryan (英国)男",
  74.     "英语 - Sonia (英国)女", "中文 - Xiaoxiao (普通话)女", "中文 - HiuGaai (粤语)女",
  75.     "中文 - 陕西小妮 (普通话)女", "韩语 - SeoYeon (韩国)女", "俄语 - Svetlana (俄国)女",
  76.     "日语 - Nanami (日本)女"
  77. ]

  78. voice_combobox = ttk.Combobox(root, values=voice_display, state="readonly")
  79. voice_combobox.set(voice_display[0])  # 默认选择第一个语音
  80. voice_combobox.pack(pady=5)

  81. # 创建生成语音的按钮
  82. generate_button = tk.Button(root, text="生成语音", command=generate_speech)
  83. generate_button.pack(pady=10)

  84. # 显示结果的标签
  85. result_label = tk.Label(root, text="")
  86. result_label.pack()

  87. # 运行主循环
  88. root.mainloop()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2025-2-10 15:01:28 | 显示全部楼层
你这个代码看起来还不错,不过在一些地方有些小问题和遗漏。我帮你补全并修正一下:

1. filetypes= 缺少内容。
2. voice_display 缺少内容。

以下是修改后的代码:


  1. import tkinter as tk
  2. from tkinter import filedialog, ttk, messagebox
  3. import subprocess
  4. import os

  5. # 创建文本转语音函数
  6. def text_to_speech(text, output_file, voice_name):
  7.     # 确保文件路径有效
  8.     if not os.path.exists(os.path.dirname(output_file)):
  9.         result_label.config(text="错误:保存路径不存在")
  10.         return
  11.    
  12.     # 检查文件是否已经存在,避免覆盖
  13.     if os.path.exists(output_file):
  14.         result_label.config(text="错误:文件已存在,请选择不同的文件名")
  15.         return
  16.    
  17.     # 清理文本中的换行符
  18.     cleaned_text = text.replace("\n", " ").replace("\r", "")  # 将换行符替换为空格或空字符
  19.    
  20.     # 调用 edge-tts 生成语音
  21.     command = f"edge-tts --text "{cleaned_text}" --voice {voice_name} --write-media {output_file}"
  22.     try:
  23.         subprocess.run(command, shell=True, check=True)
  24.         result_label.config(text=f"语音文件已生成:{output_file}")
  25.     except subprocess.CalledProcessError as e:
  26.         result_label.config(text=f"生成语音时发生错误: {e}")

  27. # 创建生成语音的回调函数
  28. def generate_speech():
  29.     text = text_input.get("1.0", "end-1c")  # 获取文本框中的文本
  30.     if text.strip():  # 确保文本框不为空
  31.         # 让用户选择保存路径
  32.         output_file = filedialog.asksaveasfilename(defaultextension=".mp3", filetypes=[("MP3 files", "*.mp3")])
  33.         if output_file:
  34.             # 获取用户选择的语音源
  35.             selected_voice = voice_combobox.get()
  36.             # 映射用户选择的语音描述到正确的语音名称
  37.             voice_mapping = {
  38.                 "英语 - Aria (美国)女": "en-US-AriaNeural",
  39.                 "英语 - Brian (美国)男": "en-US-BrianNeural",
  40.                 "英语 - Ryan (英国)男": "en-GB-RyanNeural",
  41.                 "英语 - Sonia (英国)女": "en-GB-SoniaNeural",
  42.                 "中文 - Xiaoxiao (普通话)女": "zh-CN-XiaoxiaoNeural",
  43.                 "中文 - HiuGaai (粤语)女": "zh-HK-HiuGaaiNeural",
  44.                 "中文 - 陕西小妮 (普通话)女": "zh-CN-shaanxi-XiaoniNeural",
  45.                 "韩语 - SeoYeon (韩国)女": "ko-KR-SunHiNeural",
  46.                 "俄语 - Svetlana (俄国)女": "ru-RU-SvetlanaNeural",
  47.                 "日语 - Nanami (日本)女": "ja-JP-NanamiNeural"
  48.             }
  49.             voice_name = voice_mapping.get(selected_voice, "en-US-AriaNeural")  # 默认使用英文语音
  50.             text_to_speech(text, output_file, voice_name)
  51.         else:
  52.             result_label.config(text="未选择文件路径")
  53.     else:
  54.         result_label.config(text="请输入文本")

  55. # 创建窗口
  56. root = tk.Tk()
  57. root.title("文本转语音生成器")

  58. # 设置窗口大小
  59. root.geometry("420x320")

  60. # 延迟弹出更新信息框,避免阻塞主界面
  61. root.after(500, lambda: messagebox.showinfo("更新信息", "修复了长文本中不能含有换行符的问题!\n加入了韩、日、俄语音库\n\n注意现在还没法检测输入的文本语言,\n是否与语音库匹配会报错!\n勉强能用,语音别选错了!"))

  62. # 创建文本框
  63. text_input = tk.Text(root, height=8, width=30)
  64. text_input.pack(pady=10)

  65. # 创建选择语音的下拉框
  66. voice_label = tk.Label(root, text="选择语音:")
  67. voice_label.pack()

  68. # 增加中文和英文的语音选择
  69. voice_display = [
  70.     "英语 - Aria (美国)女",
  71.     "英语 - Brian (美国)男",
  72.     "英语 - Ryan (英国)男",
  73.     "英语 - Sonia (英国)女",
  74.     "中文 - Xiaoxiao (普通话)女",
  75.     "中文 - HiuGaai (粤语)女",
  76.     "中文 - 陕西小妮 (普通话)女",
  77.     "韩语 - SeoYeon (韩国)女",
  78.     "俄语 - Svetlana (俄国)女",
  79.     "日语 - Nanami (日本)女"
  80. ]

  81. voice_combobox = ttk.Combobox(root, values=voice_display, state="readonly")
  82. voice_combobox.set("英语 - Aria (美国)女")  # 默认选择第一个语音
  83. voice_combobox.pack(pady=5)

  84. # 创建生成语音的按钮
  85. generate_button = tk.Button(root, text="生成语音", command=generate_speech)
  86. generate_button.pack(pady=10)

  87. # 显示结果的标签
  88. result_label = tk.Label(root, text="")
  89. result_label.pack()

  90. # 运行主循环
  91. root.mainloop()
复制代码


这个代码段对几个关键地方进行了修正并补完整。可以试试看这个版本是否能达到你的预期效果。如果你还有其他问题,欢迎继续提问!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-6 04:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表