TourGuilde / tts.py
buitu0's picture
Upload tts.py
9aceb31 verified
Raw
History Blame Contribute Delete
1.92 kB
import asyncio
import edge_tts
from gtts import gTTS
import os
async def generate_audio_edge(text, voice, output_file):
# Chia nhỏ văn bản thành các đoạn văn (paragraphs) để xử lý
# Giúp Edge TTS không bị quá tải và tránh lỗi file MP3 bị hỏng (giật, lag) ở phần sau
paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
with open(output_file, "wb") as f:
for para in paragraphs:
try:
communicate = edge_tts.Communicate(para, voice)
async for chunk in communicate.stream():
if chunk["type"] == "audio":
f.write(chunk["data"])
except Exception as e:
print(f"Lỗi khi đọc đoạn văn: {e}")
await asyncio.sleep(0.1) # Nghỉ một chút để tránh bị API chặn
def generate_audio_gtts(text, lang, output_file):
tts = gTTS(text=text, lang=lang)
tts.save(output_file)
def generate_audio(text, voice_style, output_file):
try:
# Map voice style to edge-tts voice
voice_mapping = {
"Nam (Tiếng Việt)": "vi-VN-NamMinhNeural",
"Nữ (Tiếng Việt)": "vi-VN-HoaiMyNeural",
"English (Male)": "en-US-ChristopherNeural",
"English (Female)": "en-US-AriaNeural"
}
voice = voice_mapping.get(voice_style, "vi-VN-HoaiMyNeural") # default female vi
asyncio.run(generate_audio_edge(text, voice, output_file))
return True
except Exception as e:
print(f"Edge TTS failed: {e}. Fallback to gTTS...")
try:
# Fallback to gTTS
lang = "vi" if "Tiếng Việt" in voice_style else "en"
generate_audio_gtts(text, lang, output_file)
return True
except Exception as e2:
print(f"gTTS also failed: {e2}")
return False