import os import tempfile import time import pygame from gtts import gTTS def speak(text): with tempfile.TemporaryDirectory() as tmpdirname: temp_path = os.path.join(tmpdirname, "speech.mp3") tts = gTTS(text=text,lang='en', tld='com') tts.save(temp_path) pygame.mixer.init() pygame.mixer.music.load(temp_path) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): time.sleep(0.1) pygame.mixer.music.unload() pygame.mixer.quit()