我正在尝试制作一个虚拟助手,我使用了tim的基本代码https://www.techwithtim.net/tutorials/voice-assistant/的技术。我试着让助理问你的名字,然后说你叫什么名字。它给了我一个奇怪的变量没有定义的错误,但我定义了它。下面是我的代码:
import os
import time
import playsound
from playsound import *
import speech_recognition as sr
from gtts import gTTS
import pyaudio
import time
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "hello" in text:
speak("hello, what is your name?")
name = r.recognize_google(audio)
time.sleep(1)
("How are you", name)
if "good" in text:
speak("Great! My name is bot by the way!")
time.sleep(99)
我得到的错误是:
builtins.NameError: name 'r' is not defined
发布于 2021-05-18 05:26:42
这是因为当你定义r时,它是一个局部变量。这意味着当函数结束时,变量将被删除。
您要做的是在函数结束时返回变量r。
像这样
import os
import time
import playsound
from playsound import *
import speech_recognition as sr
from gtts import gTTS
import pyaudio
import time
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said, r, audio
text, r, audio = get_audio()
if "hello" in text:
speak("hello, what is your name?")
name = r.recognize_google(audio)
time.sleep(1)
("How are you", name)
if "good" in text:
speak("Great! My name is bot by the way!")
time.sleep(99)
https://stackoverflow.com/questions/67577162
复制相似问题