how to play mp3

前端 未结 12 1664
醉酒成梦
醉酒成梦 2021-02-09 09:39

my problem starts here:

pyttsx and gTTS module errors

gTTS works well, takes text from text file, but first creates mp3 file, then if I want listen, I must call

12条回答
  •  迷失自我
    2021-02-09 10:17

    This will do the job and without the need for files:

    def say(text, lang='en'):
    """ Speak the provided text.
    """    
    import pygame
    from gtts import gTTS
    import io
    tts = gTTS(text=text, lang=lang, slow=False)
    pygame.mixer.init()
    pygame.init()  # this is needed for pygame.event.* and needs to be called after mixer.init() otherwise no sound is played 
    with io.BytesIO() as f: # use a memory stream
        tts.write_to_fp(f)
        f.seek(0)
        pygame.mixer.music.load(f)
        pygame.mixer.music.set_endevent(pygame.USEREVENT)
        pygame.event.set_allowed(pygame.USEREVENT)
        pygame.mixer.music.play()
        pygame.event.wait() # play() is asynchronous. This wait forces the speaking to be finished before closing f and returning
    

提交回复
热议问题