Ryanus commited on
Commit
4b22121
·
verified ·
1 Parent(s): ea714f5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import edge_tts
3
+ import gradio as gr
4
+ import os
5
+
6
+ # 定義一個異步函數來生成語音
7
+ async def generate_speech(text: str, voice: str, rate: str, pitch: str) -> str:
8
+ """
9
+ 使用 Edge TTS 生成語音並保存為音頻文件。
10
+
11
+ Args:
12
+ text (str): 要轉換為語音的文本。
13
+ voice (str): 要使用的語音名稱 (例如 "zh-CN-XiaoxiaoNeural")。
14
+ rate (str): 語速調整 (例如 "+0%", "-10%", "+20%")。
15
+ pitch (str): 音高調整 (例如 "+0Hz", "-5Hz", "+10Hz")。
16
+
17
+ Returns:
18
+ str: 生成的音頻文件的路徑。
19
+ """
20
+ output_file = "output.mp3"
21
+
22
+ # 構建 Edge TTS 命令
23
+ communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)
24
+
25
+ # 將語音寫入文件
26
+ await communicate.save(output_file)
27
+
28
+ return output_file
29
+
30
+ # 獲取可用的語音列表
31
+ async def get_voices():
32
+ """
33
+ 獲取 Edge TTS 可用的語音列表。
34
+ """
35
+ voices = await edge_tts.list_voices()
36
+ return [voice.ShortName for voice in voices]
37
+
38
+ # Gradio 介面函數
39
+ async def tts_interface(text, voice, rate_percentage, pitch_hz):
40
+ # 將百分比和 Hz 轉換為 Edge TTS 期望的格式
41
+ rate = f"{rate_percentage}%"
42
+ pitch = f"{pitch_hz}Hz"
43
+
44
+ audio_path = await generate_speech(text, voice, rate, pitch)
45
+ return audio_path
46
+
47
+ # 啟動 Gradio 介面
48
+ async def main():
49
+ voices = await get_voices()
50
+
51
+ iface = gr.Interface(
52
+ fn=tts_interface,
53
+ inputs=[
54
+ gr.Textbox(lines=5, label="輸入文本"),
55
+ gr.Dropdown(voices, label="選擇語音", value="zh-CN-XiaoxiaoNeural"), # 預設中文語音
56
+ gr.Slider(minimum=-50, maximum=50, value=0, step=1, label="語速調整 (%)"),
57
+ gr.Slider(minimum=-50, maximum=50, value=0, step=1, label="音高調整 (Hz)")
58
+ ],
59
+ outputs=gr.Audio(type="filepath", label="生成的語音"),
60
+ title="Edge TTS 語音合成",
61
+ description="輸入文本,選擇語音,調整語速和音高,然後生成語音。",
62
+ allow_flagging="never"
63
+ )
64
+
65
+ iface.launch()
66
+
67
+ if __name__ == "__main__":
68
+ asyncio.run(main())
69
+