Python 无法以我可以在 if 语句中使用它的方式识别我的语音到文本

问题描述 投票:0回答:1

我目前正在使用 python 构建一个个人助理,并且我让它在一定程度上发挥了作用。我一直在使用这个视频教程。我让助理“harvey”说出所有名义上的系统,并听听我在说什么,将其重复给我并在命令终端中打印出来,但是一旦它需要识别语音并将其与 if 语句进行比较,它不起作用并转到 else 语句。

我的代码是:

import datetime
import speech_recognition as sr 
import pyttsx3
import webbrowser
import wikipedia
import wolframalpha

#Speech Init
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id) #0, male / 1, female
activationword = 'Harvey' #should be single word

def speak(text, rate = 120):
    engine.setProperty('rate', rate)
    engine.say(text)
    engine.runAndWait()

def ParseCommand():
    listener = sr.Recognizer()
    print('Listening for a command')
    
    with sr.Microphone() as source: #uses computer default mic
        listener.pause_threshold = 2
        input_speech = listener.listen(source)
    
    try:
        print("Understanding...")
        query = listener.recognize_google(input_speech, language='en_us')
        print(f'The input speech was: {query}')

    except Exception as exception:
        print("Excuse me?")
        speak('Excuse me?')

        print(exception)
        return 'None'
    
    return query

# Main Loop
if __name__ == '__main__':
    speak('All systems nominal.')

    while True:
        #Parse as a list
        print("Test 1 Succesful")
        query = ParseCommand().lower().split()
        print("Test 2 Succesful")
        verbal= "I heard", query[0], "is that correct?"
        speak(verbal)

        if query[0] == activationword:
            print("Test 3 Succesful")
            speak('Listening')
            query.pop(0)

            #list commands
            if query[0] == 'say':
                if 'hello' in query:
                    speak('Hello Sire, What can I do for you today')

                else:
                    query.pop(0) #Removes say from the list
                    speech = ''.join(query)
                    speak(speech)

        else:
            speak("Sorry sire I'm confused")

我的猜测是错误发生在

query = ParseCommand().lower().split()
if query[0] == activationword: 

python module speech-recognition python-module assistant
1个回答
0
投票

您的代码似乎存在一些问题。

  1. 案例1

engine.setProperty('voices', voices[0].id)
行中,属性应该是
'voice'
,而不是
'voices'

  1. 案例2

query = ParseCommand().lower().split()
行中,查询的所有元素都将是小写的。所以你必须把
activationword = 'Harvey'
改成
activationword = 'harvey'

请检查并继续开发。

© www.soinside.com 2019 - 2024. All rights reserved.