File size: 1,654 Bytes
1bbda65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
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)