Search code examples
pythonpython-3.xchatbotpyttsx

pyttsx produces no sound


I am just creating a chatbot in Python. It's working well but I want to add pyttsx to this chatbot so that it could speak its output. My code is

import aiml
import sys
import pyttsx

engine = pyttsx.init()

# Create a Kernel object.
kern = aiml.Kernel()

brainLoaded = False
forceReload = False
while not brainLoaded:
    if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"):
        kern.bootstrap(learnFiles="std-startup.xml", commands="load aiml b")
        brainLoaded = True
        kern.saveBrain("standard.brn")
    else:
         try:

            kern.bootstrap(brainFile = "standard.brn")
            brainLoaded = True
        except:
            forceReload = True


print "\nINTERACTIVE MODE (ctrl-c to exit)"
while(True):

    hea = kern.respond(raw_input("> "))

    print hea
    engine.say (hea)

engine.runAndWait()

When I am running this code I am not hearing any voice but I can see chat on terminal. I want it to speak the response, too. What am I doing wrong?


Solution

  • engine.runAndWait is outside the while(True): loop, so it's unlikely to be played until the loop is interrupted.

    If you move it into the loop, and and the sound is choppy, test the code below:

    import pyttsx
    engine = pyttsx.init()
    engine.say("Oh, hello!")
    

    My experience with pyttsx is that it needs to be fed short amounts of text, otherwise the text is interrupted. I'm not sure exactly why that is, but truncating the sentences yourself and saying several phrases should suit your purpose:

    engine.say("It's nice to meet you.")
    engine.say("I hope you are doing well.")
    engine.say("Would you like to join us ")
    engine.say ("tomorrow at eight for dinner?")
    

    But you'd need to parse the text and truncate it in a way that would keep the message intact.