在tkinter上运行speech_recognition使其冻结

时间:2016-03-31 17:55:15

标签: python python-3.x tkinter speech-recognition

我正在写一个程序,你可以和它说话,它会像siri一样回应。我使用谷歌语音识别和espeak来倾听和交谈。然后将对话打印到文本框中。

当程序被要求使用语音识别进行收听时,它会冻结并再次点击GUI,然后它会显示“没有响应”,我是否正在运行此错误或是否无法在语音识别中运行语音识别tkinter

为什么会冻结?

这是我到目前为止编写的整个代码:

import tkinter as tk
from subprocess import call as say
import winsound
import speech_recognition as sr

def cbc(tex):

    return lambda : callback(tex)

def callback(tex):
    button = "Listen" 

    tex.insert(tk.END, button)
    tex.see(tk.END)# Scroll if necessary

def listen(tex):

        say('espeak '+"Say,,your,,command,,after,,the,,beep", shell=True)
        winsound.Beep(1000,500)

        ltext = 'listening...'
        tex.insert(tk.END, ltext)
        tex.see(tk.END)

        r = sr.Recognizer()

        with sr.Microphone() as source:
            damand = r.listen(source)

        damandtxt = (recognizer_google(damand))
        tex.insert(tk.END, damandtxt)
        tex.see(tk.END)



top = tk.Tk()
tex = tk.Text(master=top)
tex.pack(side=tk.RIGHT)
bop = tk.Frame()
bop.pack(side=tk.LEFT)


tk.Button(bop, text='Listen', command=lambda: listen(tex)).pack()
tk.Button(bop, text='Exit', command=top.destroy).pack()

top.mainloop()

1 个答案:

答案 0 :(得分:2)

运行脚本时,您的计算机一次只能执行一项操作。因此,如果您希望它监听,例如,计算机在执行当前命令时将无法运行任何其他命令。解决这个问题的方法是使用多个线程,这样你的计算机可以同时做两件事。查看Python的线程模块。说实话,我对这方面也不太了解,但这是我在自己的GUI中实现的。

import tkinter as tk
from subprocess import call as say
import winsound
import speech_recognition as sr

import threading

def cbc(tex):

    return lambda : callback(tex)

def callback(tex):
    button = "Listen" 

    tex.insert(tk.END, button)
    tex.see(tk.END)# Scroll if necessary

def listen(tex):
    def callback(tex):
        say('espeak '+"Say,,your,,command,,after,,the,,beep", shell=True)
        winsound.Beep(1000,500)

        ltext = 'listening...'
        tex.insert(tk.END, ltext)
        tex.see(tk.END)

        r = sr.Recognizer()

        with sr.Microphone() as source:
            damand = r.listen(source)

        damandtxt = (recognizer_google(damand))
        tex.insert(tk.END, damandtxt)
        tex.see(tk.END)

    a_thread = threading.Thread(target = callback(tex))
    a_thread.start()

top = tk.Tk()
tex = tk.Text(master=top)
tex.pack(side=tk.RIGHT)
bop = tk.Frame()
bop.pack(side=tk.LEFT)


tk.Button(bop, text='Listen', command=lambda: listen(tex)).pack()
tk.Button(bop, text='Exit', command=top.destroy).pack()

top.mainloop()

基本思想是创建一个线程对象,然后给它一个运行的函数。然后,当您想要运行此线程时,请调用线程的start()方法。绝对是read,因为当一次运行多个线程时,事情会变得多毛。