0

I had this script working to hear an audio from text with gtts without having to save the mp3, using BytesIo, but now if I do not put a time.sleep at the end I cannot hear the sound. Why? Is there a solution different from putting a pause to the end?

from gtts import gTTS
from io import BytesIO
import pygame
import time

def speak(text, language='en'):
    mp3_fo = BytesIO()
    tts = gTTS(text, lang=language)
    tts.write_to_fp(mp3_fo)
    return mp3_fo

pygame.init()
pygame.mixer.init()
# sound.seek(0)
sound = speak("Python is cool always")
pygame.mixer.music.load(sound, 'mp3')
pygame.mixer.music.play()
time.sleep(5)
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34

1 Answers1

0

Maybe because the main thread ends before the sounds play. You can try to execute your .play() in an other thread and order the main thread to wait the end of this thread ?

DamienDne
  • 27
  • 1
  • I don't know, in previous version of python it worked, so I don't know if it's because of python or because of the gtts module or the google API – PythonProgrammi Nov 08 '22 at 17:23