File size: 1,317 Bytes
cd37326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

from gtts import gTTS
import io
import base64
import tempfile

def generate_speech(text: str, lang: str = 'ar') -> tuple[str, str]:
    """Generate speech from text using Google TTS and return audio file path and base64 data."""
    try:
        # Create TTS object
        tts = gTTS(text=text, lang=lang, slow=False)

        # Save to temporary file
        temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
        temp_audio_file.close()

        tts.save(temp_audio_file.name)

        # Also create base64 version for direct playback
        audio_buffer = io.BytesIO()
        tts.write_to_fp(audio_buffer)
        audio_buffer.seek(0)
        audio_base64 = base64.b64encode(audio_buffer.read()).decode('utf-8')

        return temp_audio_file.name, f"data:audio/mp3;base64,{audio_base64}"
    except Exception as e:
        print(f"TTS Error: {e}")
        return None, None

if __name__ == "__main__":
    # Test the TTS function
    text = "مرحبا، هذا اختبار للصوت"
    file_path, audio_data = generate_speech(text)
    if file_path and audio_data:
        print(f"Audio file created: {file_path}")
        print(f"Audio data length: {len(audio_data)}")
        print("TTS test successful!")
    else:
        print("TTS test failed!")