简体   繁体   English

Python Speech_Recognition - “此音频源已在上下文管理器中”

[英]Python Speech_Recognition - "This audio source is already inside a context manager"

I am trying to run the speech recognition in the background on Linux machine, but it gives me an AssertionError saying "This audio source is already inside a context manager".我试图在 Linux 机器上的后台运行语音识别,但它给了我一个 AssertionError 说“这个音频源已经在上下文管理器中”。 Everything is working fine, when using it without threading.在没有线程的情况下使用它时,一切正常。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import speech_recognition as sr

def speech_to_text(recognizer, audio):
    try:
        print(recognizer.recognize_google(audio, language="de"))
    except sr.UnknownValueError:
        print("[!] UnknownValueError")
    except sr.RequestError as e:
        print("RequestError: ", e)

def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.adjust_for_ambient_noise(source)
        stop_listening = r.listen_in_background(source, speech_to_text)
        #stop_listening()
        #audio = r.listen(source)
        #print(r.recognize_google(audio))

if __name__ == "__main__":
    get_audio()

Thanks in advance!提前致谢!

The issue is with your instance of microphone before your context manager 'with'.问题出在上下文管理器“with”之前的麦克风实例。 Try this尝试这个


def get_audio():
    r = sr.Recognizer()
    mic = sr.Microphone()
    with mic as source:
        print("Listening...")
        r.adjust_for_ambient_noise(source)
        try:
           stop_listening = r.listen_in_background(source, speech_to_text)
        except:
            print('please say that again')
            return get_audio()
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM