|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
tts = gTTS(text=text, lang=lang, slow=False) |
|
|
|
|
|
|
|
|
temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') |
|
|
temp_audio_file.close() |
|
|
|
|
|
tts.save(temp_audio_file.name) |
|
|
|
|
|
|
|
|
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__": |
|
|
|
|
|
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!") |
|
|
|