python idle使用kivy框架打包手机应用,在手机界面按下“开始录音”的按钮时调用百度api开始录音并识别,同时在文本框中展现识别结果,按下”清空”按钮清除文本框内容;当识别出“加载样品溶液”或者按下界面上的”加载样品溶液“按钮时调用手机api蓝牙向hc-05型号的蓝牙发送字母a,识别出“加载清洗液一“的时候通过蓝牙发送字母b;识别出“加载清洗液二”或按下按钮的时候发送字母c,识别出“加载洗脱溶液”时发送字母d,按下“总操作”的按钮时发送字母e完整代码生成
时间: 2023-09-06 12:10:33 浏览: 136
python IDLE shell 中文界面
由于代码较长,无法在此处完整展示,请参考以下代码:
```python
import os
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import speech_recognition as sr
import serial
# 通过Builder.load_file加载.kv文件
Builder.load_file("app.kv")
class MainApp(App):
def build(self):
return RootWidget()
class RootWidget(BoxLayout):
# 获取文本框对象
txt_input = ObjectProperty(None)
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
self.recognizer = sr.Recognizer()
self.microphone = sr.Microphone()
self.ser = serial.Serial('/dev/tty.HC-05-DevB', 9600, timeout=1)
def on_start_recording(self):
with self.microphone as source:
self.recognizer.adjust_for_ambient_noise(source)
audio = self.recognizer.listen(source)
try:
text = self.recognizer.recognize_baidu(audio, appid='xxx', api_key='xxx', secret_key='xxx')
self.txt_input.text = text
if "加载样品溶液" in text:
self.ser.write(b'a')
elif "加载清洗液一" in text:
self.ser.write(b'b')
elif "加载清洗液二" in text:
self.ser.write(b'c')
elif "加载洗脱溶液" in text:
self.ser.write(b'd')
except sr.UnknownValueError:
print("Baidu Speech Recognition could not understand audio")
except sr.RequestError as e:
print(f"Could not request results from Baidu Speech Recognition service; {e}")
def on_clear_text(self):
self.txt_input.text = ""
def on_load_sample_solution(self):
self.ser.write(b'a')
def on_load_cleaning_solution1(self):
self.ser.write(b'b')
def on_load_cleaning_solution2(self):
self.ser.write(b'c')
def on_load_elution_solution(self):
self.ser.write(b'd')
def on_total_operation(self):
self.ser.write(b'e')
if __name__ == '__main__':
MainApp().run()
```
同时,需要在同级目录下新建一个名为`app.kv`的文件,并添加以下代码:
```python
<RootWidget>:
BoxLayout:
orientation: "vertical"
TextInput:
id: txt_input
readonly: True
BoxLayout:
size_hint_y: None
height: "48dp"
Button:
text: "开始录音"
on_release: root.on_start_recording()
Button:
text: "清空"
on_release: root.on_clear_text()
BoxLayout:
size_hint_y: None
height: "48dp"
Button:
text: "加载样品溶液"
on_release: root.on_load_sample_solution()
Button:
text: "加载清洗液一"
on_release: root.on_load_cleaning_solution1()
Button:
text: "加载清洗液二"
on_release: root.on_load_cleaning_solution2()
Button:
text: "加载洗脱溶液"
on_release: root.on_load_elution_solution()
BoxLayout:
size_hint_y: None
height: "48dp"
Button:
text: "总操作"
on_release: root.on_total_operation()
```
请注意,代码中的`appid`、`api_key`、`secret_key`需要自己到百度API平台申请并填写。此外,代码中的`/dev/tty.HC-05-DevB`是串口号,需要根据实际情况进行更改。
阅读全文