我需要运行两个循环,一个用于侦听语音命令,另一个用于保持与MQTT代理的连接,并侦听/发布MQTT主题,在发出语音命令时进行发布。问题是,我不知道最好的办法来设置这个。在MQTT等待语音命令执行函数的情况下,如何将这些设置为同时运行/从哪里开始研究解决方案?上课?多线程?不知道从哪里开始。在
另外-旁注-这种语音识别(pocketsphinx)是绝对可怕的。它有5%的时间会出现开/关的情况,每隔一段时间就会给出各种随机响应。如果你能用一个更好的模块,或者用pocketsphinx编码来更准确的话,你可以给我指出一个正确的方向(我已经注册了一个Google云语音API密钥,但是还没有收到)。在
这是密码
在语音.py公司名称:
import pyaudio, os
import mqttPublisher
import speech_recognition as sr
def mainfunction(source):
audio = r.listen(source)
user = r.recognize_sphinx(audio)
print(user)
if user == 'on':
mqttPublisher.led_on()
elif user == 'off':
mqttPublisher.led_off()
if __name__ == '__main__':
r = sr.Recognizer()
with sr.Microphone() as source:
while 1:
mainfunction(source)
在mqttPublisher.py公司名称:
^{pr2}$
根据hardillb的建议,我研究了线程并发现了一些问题,可以用类来解决这个问题。我以前的答案是:
Running infinite loops using threads in python
Thread issue while subscribing to MQTT in Python using Paho MQTT
下面是按预期工作的完整代码。它启动语音模块和Mqtt客户机,等待yes/no(这是我能让语音模块识别的唯一一致的单词…)并在收到相应命令时打开/关闭我的Aruidno指示灯。对于那些感兴趣的人,我也将包括Arduino代码。IP地址192.168.1.2指向我的Raspberry Pi,它正在运行一个Mosquitto代理来处理MQTT主题。在
在语音.py公司名称:
在mqttPublisher.py公司名称:
^{pr2}$Arduino代码:
paho.mqtt.client.loop_start()
启动一个线程来处理它的网络循环。打一次电话就可以了。在相关问题 更多 >
编程相关推荐