我怎样才能让Python等我说完呢?

1mrurvl1  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(154)

我正在写一个程序来识别来自麦克风的语音,代码将相应地进行处理。我为此编写的代码如下。

import speech_recognition as sr
import webbrowser
import pyttsx
from time import sleep

engine = pyttsx.init()
engine.setProperty('rate', 70)
r = sr.Recognizer()

def recognize(audio):
    try:
        return r.recognize(audio)
    except LookupError, e:
        print e
    return ''
with sr.Microphone() as source:
    while True:
        engine.say("Hi How can i help you ?")
        sleep(0.15)
        print "Start Speaking"
        audio = r.listen(source)
        words = recognize(audio)
        print("You said " + words)
        if words == "Facebook":
            engine.say("Shall i open the Facebook page for you ?")
            engine.runAndWait()
            audio = r.listen(source)
            words = recognize(audio)
            if words == "Yes":
                webbrowser.open('https://www.facebook.com')
        elif words == "stop":
            break

在这里,我也尝试了睡眠,但在引擎说话之前,我可以看到文本Start Speaking打印出来。除了睡眠,还有什么好的方法可以在麦克风中捕捉语音,然后等待说话或长时间沉默吗?

ylamdve6

ylamdve61#

该方法:

engine.runAndWait()

等待语音完成。您不仅需要在engine.say("Shall i open the Facebook page for you ?")之后使用它,还需要在engine.say("Hi How can i help you ?")之后而不是sleep之后使用它

ogq8wdun

ogq8wdun2#

我通常使用全局变量,这是不赞成的,但以下是正确的,我认为?以下两个def的应该有帮助...

# contains reusable print and speech
def output_modes(output):
    engine = pyttsx3.init()
    print(f"Output: {output}")
    engine.say(output)
    engine.runAndWait()

# contains reusable grabbing audio
def input_modes():

    r1 = sr.Recognizer()
    mic1 = sr.Microphone()

    with mic1:
        try:
            output = r1.recognize_google(r1.listen(mic1))
            output_modes()
        except sr.UnknownValueError:
            output = "Unknown Error M1"
            output_modes()
        except sr.RequestError as e:
            output = "Error M2; {0}".format(e)
            output_modes()

例如,您应该能够编写一个While循环,该循环可以调用input_modes()来收听或调用output_modes来讲话

def interact():
    if input == 'Hello':
        output = 'Hi there'
        output_modes

相关问题