使用库pyttsx3

时间:2019-06-12 13:02:03

标签: python-3.x voice-recognition pyttsx

我已经为语音识别机器人编写了一个演示项目。但是我遇到了一些错误,表明该对象没有属性。我已附上以下代码

def speak(audio):
    print('Computer: ' + audio)
    engine.say(audio)
     engine.runAndWait()

myCommand的功能:

def myCommand():

r = sr.Recognizer()                                                                                   
with sr.Microphone() as source:                                                                       
    print("Listening...")
    r.pause_threshold =  1
    audio = r.listen(source)
try:
    query = r.recognize_google(audio, language='en-in')
    print('User: ' + query + '\n')

except sr.UnknownValueError:
    speak('Sorry sir! I didn\'t get that! Try typing the command!')
    query = str(input('Command: '))

    return query

主要功能:

if __name__ == '__main__':

while True:

    query = myCommand()
    print(query)
    query = query.lower()
    print(query)

    if 'open youtube' in query:
        speak('okay')
        webbrowser.open('www.youtube.com')

    elif 'open google' in query:
        speak('okay')
        webbrowser.open('www.google.co.in')          

    else:
        query = query
        speak('Searching...')
        try:
            try:
                res = client.query(query)
                results = next(res.results).text
                speak('WOLFRAM-ALPHA says - ')
                speak('Got it.')
                speak(results)

            except:
                results = wikipedia.summary(query, sentences=2)
                speak('Got it.')
                speak('WIKIPEDIA says - ')
                speak(results)

        except:
            webbrowser.open('www.google.com')

    speak('please give me Next Command! Sir!')

query = query.lower() AttributeError:'NoneType'对象没有属性'lower'

1 个答案:

答案 0 :(得分:0)

我在这里看到的问题仅仅是代码中的缩进。

with sr.Microphone() as source:                                                                       
   print("Listening...")
   r.pause_threshold =  1
   audio = r.listen(source)
try:
query = r.recognize_google(audio, language='en-in')
print('User: ' + query + '\n')

except sr.UnknownValueError:
  speak('Sorry sir! I didn\'t get that! Try typing the command!')
  query = str(input('Command: '))

return query

在您的代码中,return语句位于except块内,只需要将其返回到外部即可。编码愉快。