29 lines
No EOL
680 B
Python
29 lines
No EOL
680 B
Python
|
|
|
|
|
|
from gtts import gTTS
|
|
import os
|
|
|
|
def text_to_speech(text, lang="en", filename="output.mp3"):
|
|
"""
|
|
Convert text to speech and save as MP3.
|
|
|
|
Args:
|
|
text (str): Text to convert
|
|
lang (str): Language code ('en' for English, 'es' for Spanish)
|
|
filename (str): Output file name
|
|
"""
|
|
try:
|
|
tts = gTTS(text=text, lang=lang)
|
|
tts.save(filename)
|
|
print(f"Saved: {filename}")
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
# --- Examples ---
|
|
|
|
# English
|
|
text_to_speech("Hello, this is a test.", lang="en", filename="english.mp3")
|
|
|
|
# Spanish
|
|
text_to_speech("Hola, esto es una prueba.", lang="es", filename="spanish.mp3") |