创建语音识别循环

时间:2019-10-03 20:10:33

标签: python speech-recognition

我正在用python创建语音助手,我想知道如何进行循环,以便每次助手响应时,麦克风都会被激活,以便我可以再次询问他

#Use Google TTS for say something
def speak(text):
    tts = gTTS(text=text, lang="es", slow=False)
    filename = "voiceww.mp3"
    tts.save(filename)
    playsound.playsound(filename)

#Use mic for get my voice
def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Di algo')
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
        said = ""

#Print the answer in console
        try:
            #print('Listo')
            said = r.recognize_google(audio, language='es')
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said
#Here the function activates
text = get_audio()

#This is a example question
if 'hello computer' in text:
    speak('Hi! How are you?')

#This is where I want to turn on the microphone again, process my voice and say the answer and so on to infinity

1 个答案:

答案 0 :(得分:0)

#Use Google TTS for say something
def speak(text):
    tts = gTTS(text=text, lang="es", slow=False)
    filename = "voiceww.mp3"
    tts.save(filename)
    playsound.playsound(filename)

#Use mic for get my voice
def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Di algo')
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
        said = ""

#Print the answer in console
        try:
            #print('Listo')
            said = r.recognize_google(audio, language='es')
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said

这是打开麦克风的方式:

while True:
    # Here the function activates
    text = get_audio().lower
    # These are examples
    if 'hello computer' in text:
        speak('Hi! How are you?')
    elif "good morning" in text:
        speak("Hey good morning")