Spaces:
Sleeping
Sleeping
| from gtts import gTTS | |
| from pydub import AudioSegment | |
| import os | |
| from dotenv import load_dotenv # Optional, only if you need environment variables | |
| import pygame | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| # Optional, only if you have any environment variables to load | |
| load_dotenv() | |
| def text_to_speech_with_gtts(text, mp3_output_path): | |
| """ | |
| Converts text to speech using gTTS, saves it as MP3, and optionally converts it to WAV. | |
| Args: | |
| - text (str): The text that will be converted to speech. | |
| - mp3_output_path (str): The path where the MP3 file will be saved. | |
| - wav_output_path (str, optional): If provided, will save the converted WAV file here. | |
| """ | |
| try: | |
| # Convert text to speech | |
| print("Converting text to speech...") | |
| tts = gTTS(text=text, lang='en') | |
| tts.save(mp3_output_path) | |
| print(f"MP3 file saved to {mp3_output_path}") | |
| # Initialize pygame mixer | |
| pygame.mixer.init() | |
| # Play the MP3 file | |
| print("Playing the MP3 file...") | |
| pygame.mixer.music.load(mp3_output_path) | |
| pygame.mixer.music.play() | |
| while pygame.mixer.music.get_busy(): | |
| pygame.time.Clock().tick(14) | |
| print("Audio playback finished.") | |
| except Exception as e: | |
| print(f"Error during text-to-speech conversion: {e}") | |
| # Example usage | |
| # text = "Hello my name is waris. i am from islamabad, Right now i am struggling to get the job in the field of Art" | |
| # mp3_file = r"C:\Users\HP\Desktop\ChatWithDoctorAny\ChatWithDoctorAny\output.mp3" | |
| # text_to_speech_with_gtts(text, mp3_file) | |