离线语音识别+青云客语音机器人(幼儿园级别教程)
1、使用步骤
确保已安装以下库:
pip install vosk sounddevice requests pyttsx3
2、下载 Vosk 模型:
下载适合的中文模型,如 vosk-model-small-cn-0.22。
下载地址:
https://alphacephei.com/vosk/models
将模型解压后放置在代码中指定的路径 MODEL_PATH。
我选择放到项目的根目录下
如下图:
3、插麦克风
记得插个耳机当麦克风哦!!!
4、完整代码
import os
import sounddevice as sd
import queue
import vosk
import sys
import json
import pyttsx3
import requests
import threading
# 初始化语音合成引擎
def init_tts():
tts_engine = pyttsx3.init()
tts_engine.setProperty('rate', 150) # 设置语速
tts_engine.setProperty('volume', 1.0) # 设置音量
return tts_engine
# 语音输出函数
def speak(tts_engine, text):
tts_engine.say(text)
tts_engine.runAndWait()
# 聊天机器人接口
class ChatBot:
def __init__(self, api_url, key="free", appid="0"):
self.api_url = api_url
self.key = key
self.appid = appid
def send_message(self, message):
params = {
"key": self.key,
"appid": self.appid,
"msg": message
}
try:
response = requests.get(self.api_url, params=params)
response.raise_for_status() # 检查请求是否成功
data = response.json()
if data.get("result") == 0:
return data.get("content")
else:
return "对不起,我无法处理您的请求。"
except requests.RequestException as e:
return f"请求失败:{e}"
# 初始化模型路径
MODEL_PATH = "vosk-model-small-cn-0.22" # 替换为模型的路径
if not os.path.exists(MODEL_PATH):
print(f"模型路径不存在: {MODEL_PATH}")
sys.exit(1)
# 加载 Vosk 模型
try:
model = vosk.Model(MODEL_PATH)
print(f"模型加载成功: {MODEL_PATH}")
except Exception as e:
print(f"加载模型时出错: {e}")
sys.exit(1)
q = queue.Queue()
stop_signal = threading.Event()
# 音频流回调函数
def callback(indata, frames, time, status):
if status:
print(f"状态错误: {status}", file=sys.stderr)
q.put(bytes(indata))
# 实时语音识别函数
def recognize(tts_engine, chatbot):
print("请开始说话...输入 'q' 并按回车退出。")
try:
with sd.RawInputStream(samplerate=16000, blocksize=8000, dtype="int16",
channels=1, callback=callback):
rec = vosk.KaldiRecognizer(model, 16000)
while not stop_signal.is_set():
try:
# 设置超时,避免队列阻塞导致无法响应中断
data = q.get(timeout=0.5)
if rec.AcceptWaveform(data):
result = json.loads(rec.Result())
recognized_text = result.get('text', '')
if recognized_text:
print(f"\n你: {recognized_text}")
# 调用聊天机器人
bot_response = chatbot.send_message(recognized_text)
print(f"机器人: {bot_response}")
# 语音输出机器人回复
speak(tts_engine, bot_response)
else:
partial_result = json.loads(rec.PartialResult()).get('partial', '')
if partial_result:
print(f"\r临时识别中: {partial_result}", end="")
except queue.Empty:
# 超时后检查停止信号
continue
except Exception as e:
print(f"发生错误: {e}")
finally:
print("清理资源并退出。")
# 主线程监听用户输入
def listen_for_exit():
while True:
user_input = input()
if user_input.strip().lower() == 'q':
stop_signal.set()
print("退出指令收到,程序即将退出。")
break
if __name__ == "__main__":
# 初始化语音合成引擎
tts_engine = init_tts()
# 初始化聊天机器人
chatbot = ChatBot(api_url="http://api.qingyunke.com/api.php")
# 欢迎语音介绍
welcome_message = "我是小菲菲,很高兴为你服务!"
print(f"机器人: {welcome_message}")
speak(tts_engine, welcome_message)
# 创建监听输入的线程
input_thread = threading.Thread(target=listen_for_exit)
input_thread.daemon = True
input_thread.start()
# 启动实时语音识别和对话
recognize(tts_engine, chatbot)
感谢您的支持和关注!!
也支持您的继续创新!!