【问题标题】:Python speech_recognition IF Speech not recognisedPython speech_recognition 如果语音无法识别
【发布时间】:2026-01-25 03:30:02
【问题描述】:

我是一名葡萄牙高中生,如果我没有把自己说得很清楚,我很抱歉,但我会尽力解释我的问题。 所以对于这个项目,我需要制作一个程序来识别语音并按照指示去做。但是,如果语音无法识别,我希望程序尝试直到它最终捕捉到所说的内容。但是我真的不知道该怎么做,因为这个“错误”不断出现:Error

如果有人想提供帮助,这里是代码:

import speech_recognition as sr
import subprocess as sp
import os

def ouvir_microfone():

   audio_Input = sr.Recognizer()

   with sr.Microphone() as source:
           
               Ray = "ON"
               Open = "Open"

               print("Hello my name is Ray pleased to help you")

               audio_Input.adjust_for_ambient_noise(source)
               print("Say something: ")
               audio = audio_Input.listen(source)
               
               frase = audio_Input.recognize_google(audio,language='en-US')

               if ValueError: print("Speech not recognised")
               else: print("You said: " + frase)

               if Open in frase:
                   print('sucess') 
ouvir_microfone()

【问题讨论】:

标签: python speech-recognition


【解决方案1】:
import speech_recognition as sr
import subprocess as sp
import os

def ouvir_microfone():

    audio_Input = sr.Recognizer()

    with sr.Microphone() as source:
        
        Ray = "ON"
        Open = "Open"

        print("Hello my name is Ray pleased to help you")

        audio_Input.adjust_for_ambient_noise(source)
        print("Say something: ")
        audio = audio_Input.listen(source)
        try:
            # valid
            frase = audio_Input.recognize_google(audio,language='en-US')
            print("You said: " + frase)
        except: 
            # google could not validate
            print("Speech not recognised")
            return False

        if Open in frase:
            print('sucess') 
        return True
while True:
    if ouvir_microfone():
        # got a valid response
        break

可用作实体模板。作为旁注,一些进口产品也仍未使用。如果无法识别语音,则捕获异常并返回 False,然后重试。 google语音识别python库在无法读取可区分语音的情况下抛出异常。

【讨论】:

  • 感谢您的帮助,Og 程序员解决问题的速度让我感到惊讶(即使是这样的基本问题),再次感谢您,关于导入我将在以后使用它们哈哈他们在那里只是为了让我以后能记住
【解决方案2】:

使用try和异常处理错误

   try:
        frase = audio_Input.recognize_google(audio,language='en-US')
        print("You said: " + frase)
    except ValueError: 
        print("Speech not recognised")
    if Open in frase:
        print('sucess') 

           

【讨论】:

  • 感谢您的帮助,它工作得很好,希望我能支持您的评论,但似乎我的帐户仍然是最近的哈哈