Ai
1 Star 0 Fork 0

从一开始/speech python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
speech.py 2.52 KB
一键复制 编辑 原始数据 按行查看 历史
从一开始 提交于 2025-07-23 17:32 +08:00 . 优化
from flask import Flask, request, jsonify
from flask_cors import CORS # 引入 Flask-CORS
import json
import pyaudio
from vosk import Model, KaldiRecognizer
import pyttsx3
from mqtt_client import send_mqtt_message
app = Flask(__name__)
CORS(app) # 启用 CORS
# 初始化语音引擎
engine = pyttsx3.init()
# 设置中文语音(根据系统可用语音选择)
voices = engine.getProperty('voices')
for voice in voices:
if 'chinese' in voice.id.lower() or 'china' in voice.id.lower():
engine.setProperty('voice', voice.id)
break
def speak(text):
"""使用语音引擎朗读文本"""
print(f"播放语音: {text}")
engine.say(text)
engine.runAndWait()
# 指定模型路径(相对路径)
model_path = "./vosk-model-small-cn-0.22"
model = Model(model_path)
# 读取 responses.json 文件
try:
with open('./responses.json', 'r', encoding='utf-8') as file:
keyword_responses = json.load(file)
except FileNotFoundError:
print("未找到 responses.json 文件,请检查文件是否存在。")
keyword_responses = {}
@app.route('/recognize', methods=['POST'])
def recognize():
try:
audio_data = request.data
rec = KaldiRecognizer(model, 16000)
if rec.AcceptWaveform(audio_data):
result = json.loads(rec.Result())
text = result["text"].strip().replace(" ", "")
if text:
print(f"识别结果: {text}")
# 检查关键词并播放响应或发送MQTT消息
for keyword, response in keyword_responses.items():
if keyword in text:
if isinstance(response, str):
# speak(response)
return jsonify({"result": response})
else:
# speak("已发送指令")
print(f"发送消息 ({response})")
topic = response["topic"]
message = json.dumps(response["message"])
send_mqtt_message(topic, message)
return jsonify({"reg" : f"识别结果: {text}", "result": "已发送指令", "msg": response })
return jsonify({ "reg" : f"识别结果: {text}" , "result": "未找到匹配的关键词"})
return jsonify({"result": "识别失败"})
except Exception as e:
return jsonify({"result": f"服务端错误: {str(e)}"})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/onlyMeStyle/speech-python.git
git@gitee.com:onlyMeStyle/speech-python.git
onlyMeStyle
speech-python
speech python
main

搜索帮助