IFRAME SYNC
from gtts import gTTS
import playsound
def text_to_speech(text, language='en', output_file='output.mp3'):
"""
Convert text to speech and save the audio file.
:param text: The text to be converted to speech.
:param language: The language of the text (default is English).
:param output_file: The name of the output audio file (default is 'output.mp3').
"""
# Create a gTTS object
tts = gTTS(text=text, lang=language, slow=False)
# Save the speech as an audio file
tts.save(output_file)
# Play the generated audio file
playsound.playsound(output_file)
if __name__ == "__main__":
# Example usage
input_text = "Hello, this is a text-to-speech converter example."
text_to_speech(input_text)from gtts import gTTS
import os
import platform
import playsound
def text_to_speech(text, language='en', output_file=None):
"""
Convert text to speech and save the audio file.
:param text: The text to be converted to speech.
:param language: The language of the text (default is English).
:param output_file: The name of the output audio file (default is None).
If None, user will be prompted to enter the file path.
"""
# Create a gTTS object
tts = gTTS(text=text, lang=language, slow=False)
# Get the output file path
if output_file is None:
output_file = input("Enter the output file path (e.g., 'output.mp3'): ")
try:
# Save the speech as an audio file
tts.save(output_file)
# Play the generated audio file
play_audio(output_file)
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Clean up: remove the temporary audio file
if os.path.exists(output_file):
os.remove(output_file)
IFRAME SYNC
def play_audio(file_path):
"""
Play the audio file using an appropriate player based on the operating system.
:param file_path: The path to the audio file.
"""
system = platform.system().lower()
if system == "darwin": # macOS
os.system(f"afplay {file_path}")
elif system == "linux":
os.system(f"aplay {file_path}")
elif system == "windows":
playsound.playsound(file_path)
else:
print("Unsupported operating system for audio playback.")
if __name__ == "__main__":
# Example usage
input_text = "Hello, this is an extended text-to-speech converter example."
text_to_speech(input_text)
Comments
Post a Comment