How to make Python speak

前端 未结 13 1199
时光说笑
时光说笑 2020-11-30 20:34

How could I make Python say some text?

I could use Festival with subprocess but I won\'t be able to control it (or maybe in interactive mode, but it won\'t be clean)

13条回答
  •  一生所求
    2020-11-30 21:02

    I prefer to use the Google Text To Speech library because it has a more natural voice.

    from gtts import gTTS
    def speak(text):
      tts = gTTS(text=text, lang="en")
      filename = "voice.mp3"
      tts.save(filename)
    

    There is one limitation. gTTS can only convert text to speech and save. So you will have to find another module or function to play that file. (Ex: playsound)

    Playsound is a very simple module that has one function, which is to play sound.

    import playsound
    def play(filename):
      playsound.playsound(filename)
    

    You can call playsound.playsound() directly after saving the mp3 file.

提交回复
热议问题