File size: 1,924 Bytes
06281e0
 
 
 
 
 
9aceb31
 
 
 
 
 
 
 
 
 
 
 
 
 
06281e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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