0

当我运行此代码并且我已经检查了很多次时,Python 给出了一个错误。这里的源是麦克风,但它一直在询问“源”的值。我该怎么办。我应该将什么参数传递给“源”?

import pyttsx3
import speech_recognition as sr
#Required Modules

engine = pyttsx3.init()
r = sr.Recognizer
#Initializes variable (Avoiding Time Delay)

def Speak(audio):
    engine.say(audio)
    engine.runAndWait()
#Defining the function Speak() for Audio Output

def Listen():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise
        print("Listening")
        voice = r.listen(source)
        print("Done Listening")
        a = r.recognize_google(voice)
        a = a.lower()
        print("You asked - "+a)    
#Defining the function Listen() for Audio Input (INTERNET REQUIRED)

while True:    
    Speak("Ask Me Some Questions")
    #Speaks

    Listen()
    #Listens

    try:
        if a == "how are you":
            print("I'm Fine Sir")
            Speak("I'm Fine Sir") 
    #Tries to do the program without error
    
    except:
        print("Error Occured!!!")
    #If error occured, this will be the Output                   

#Looped

此代码给出错误,

Traceback (most recent call last):
  File "c:\Users\Vishal\AppData\Local\Programs\Python\Python39\Python Projects\Speech.py", line 29, in <module>
    Listen()
  File "c:\Users\Vishal\AppData\Local\Programs\Python\Python39\Python Projects\Speech.py", line 18, in Listen
    voice = r.listen(source)
TypeError: listen() missing 1 required positional argument: 'source'

究竟是什么错误以及如何解决?(我是python的初学者,所以放轻松)

4

1 回答 1

1

这是更新的代码

1.您必须始终首先阅读文档应该有 sr.Recognizer()

2.如果您正在创建方法,那么对于交互,您应该返回值

import pyttsx3
import speech_recognition as sr
#Required Modules

engine = pyttsx3.init()
r = sr.Recognizer()
#Initializes variable (Avoiding Time Delay)

def Speak(audio):
    engine.say(audio)
    engine.runAndWait()
#Defining the function Speak() for Audio Output

def Listen():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Listening")
        voice = r.listen(source)
        print("Done Listening")
        a = r.recognize_google(voice)
        a = a.lower()
        print("You asked - "+a)   
        return a
#Defining the function Listen() for Audio Input (INTERNET REQUIRED)

while True:    
    Speak("Ask Me Some Questions")
    #Speaks

    a=Listen()
    #Listens

    try:
        if a == "how are you":
            print("I'm Fine Sir")
            Speak("I'm Fine Sir") 
    #Tries to do the program without error
    
    except:
        print(a)
        print("Error Occured!!!")
    #If error occured, this will be the Output                   

#Looped
于 2021-03-30T10:45:57.177 回答