Python google 一段时间后语音识别模块不工作

Python google speech recognition module doesn't work after a while

我正在尝试使用 Python 为名为 "Emma" 的计算机创建类似 Alexa 的应用程序。 通过使用 Speech Recognition 模块,它将使用麦克风作为来源来收听用户的声音。 它工作正常,但在回答或执行一些类似搜索的操作后,它会冻结并且不再工作。

我想也许语音识别的使用时间有限,但搜索后我一无所获。现在我只是不知道这是因为语音识别或其他一些模块,如 GTTS (Google Text To Speech).

如果您需要查看完整代码,这里是我存储库的 link:https://github.com/sina1mhi/emma_virtual_assistant

请告诉我您解决问题的方法。

下面是部分语音识别代码:

def record_audio(ask=False, lang="en-US"):
    with sr.Microphone() as source:  # microphone as source
        print("Emma: I'm listening")
        if ask:
            speak(ask)
        time.sleep(1)
        audio = r.listen(source)  # listen for the audio via source
        voice_data = ''
        try:
            voice_data = r.recognize_google(
                audio, language=lang)  # convert audio to text
        except sr.UnknownValueError:  # error: recognizer does not understand
            speak("I did'nt get that")
            exit()
        except sr.RequestError:
            # error: recognizer is not connected
            speak('Sorry, the service is down')
            exit()
        print(f">> {voice_data.lower()}")  # print what user said
        return voice_data.lower()

阅读 Speech Recognition Library Reference 后,我发现与其使用识别器的 listen 方法,不如使用 record 方法 并设置持续时间参数。


代码如下:

def record_audio(ask=False, lang="en-US"):
    # Change the sample_rate to 16000 good quality and better recognition
    # higher sample rate means slower app.
    with sr.Microphone(sample_rate=12000) as source:  # microphone as source
        print("Emma: I'm listening")
        audio = r.record(source, duration=5)  # listen for the audio via source
        print("Emma: Microphone turned off, processing...")
        voice_data = ''
        try:
            voice_data = r.recognize_google(
                audio, language=lang)  # convert audio to text
        except sr.UnknownValueError:  # error: recognizer does not understand
            speak("I did'nt get that")
            exit()
        except sr.RequestError:
            # error: recognizer is not connected
            speak('Sorry, the service is down')
            exit()
        print(f">> {voice_data.lower()}")  # print what user said
        return voice_data.lower()