语音识别在Python中显示错误(位置参数错误)

2024-05-23 13:43:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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的初学者,所以对我放松点)


Tags: the代码importsourceforas错误listen
1条回答
网友
1楼 · 发布于 2024-05-23 13:43:44

这是更新后的代码

1.您必须首先查看文档,应该有高级识别器()

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

相关问题 更多 >