问题描述
我经历了与此主题相关的所有类似问题,并尝试了所有方法,但无济于事。
我尝试了以下链接的解决方案: speech recognition python stopped in listen SpeechRecognition producing OSError: No Default Input Device Available Python,Speech Recognition stuck at 'Listening...' speech recognition python code not working等。
import speech_recognition as sr
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source,duration=5)
print("listening... ")
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
except sr.UnkNownValueError:
print("Google Speech Recognition Could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return said.lower()
print(get_audio())
我遇到的错误是:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
以下命令被卡在“说某事..”而没有执行任何操作。
python -m speech_recognition
import pyaudio
print(pyaudio.pa.get_default_input_device())
输出:
OSError: No Default Input Device Available
我在做什么错了?
解决方法
如上面的评论所述,您似乎没有任何可用的麦克风。
在使用语音识别时,我通常会在听之前询问用户使用哪种设备。
例如,使用这个实现:
# Identify the microphone device to use
def get_microphone_device():
microphone_list = []
for index,name in enumerate(sr.Microphone.list_microphone_names()):
microphone_list.append("Microphone {1} `(device_index={0})`".format(index,name))
questions = [
inquirer.List('microphone',message = "What Microphone will you use?",choices = microphone_list,),]
answers = inquirer.prompt(questions)
microphone = answers["microphone"]
microphone = re.search("(?=`)(.*)",microphone).group(0)
device = re.search("[0-9]",microphone).group()
return device
然后,要使用设备并获取消息,您可以按照您的操作进行操作,例如:
# Listen to the speaker through the microphone device
def get_speech(device):
rec = sr.Recognizer()
with sr.Microphone(device_index=int(device)) as source:
print("Speak,we are listening:")
audio = rec.listen(source)
try:
text = rec.recognize_google(audio)
print("You said: \"{}\"".format(text))
except:
print("Sorry,we couldn't recognize what you said")
return text
Here is an example of the full implementation
希望对您有所帮助!