qwerlol123? 6 months ago
parent 5caac9d3a0
commit df68003ff7

@ -1,121 +0,0 @@
import pyttsx3
import tkinter as tk
import threading
import speech_recognition as sr
# Initialize speech synthesis object
talker = pyttsx3.init()
# Initialize speech recognition object
recognizer = sr.Recognizer()
# Login credentials
userName = "admin"
userPass = "123"
# Create chat window
def chat_window():
chat_window = tk.Tk()
chat_window.title("对话")
chat_window.geometry("800x400")
def chat():
question = input_entry.get()
answer = question.strip("吗??" + "!")
if question == "不聊了拜拜":
talker.say("好的,拜拜就拜拜!")
talker.runAndWait()
chat_window.destroy()
else:
chat_text.insert(tk.END, "你: " + question + "\n")
chat_text.insert(tk.END, "机器人的回答:" + answer + "\n")
talker_thread = threading.Thread(target=speak, args=(answer,))
talker_thread.start()
input_entry.delete(0, tk.END)
def speak(answer):
talker.say(answer)
talker.runAndWait()
def voice_recognition():
with sr.Microphone() as source:
print("请说话...")
audio = recognizer.listen(source)
try:
print("识别中...")
question = recognizer.recognize_google(audio, language="zh-CN")
print("你说: " + question)
answer = question.strip("吗??" + "!")
if question == "不聊了拜拜":
talker.say("好的,拜拜就拜拜!")
talker.runAndWait()
chat_window.destroy()
else:
chat_text.insert(tk.END, "你: " + question + "\n")
chat_text.insert(tk.END, "机器人的回答:" + answer + "\n")
talker_thread = threading.Thread(target=speak, args=(answer,))
talker_thread.start()
except sr.UnknownValueError:
print("抱歉, 未能识别,请重试")
chat_text = tk.Text(chat_window)
chat_text.pack()
input_entry = tk.Entry(chat_window)
input_entry.pack()
send_button = tk.Button(chat_window, text="发送", command=chat)
send_button.pack()
voice_button = tk.Button(chat_window, text="语音识别", command=voice_recognition)
voice_button.pack()
chat_window.mainloop()
# 创建登录窗口
def login_window():
login_window = tk.Tk()
login_window.title("登录")
# 获取屏幕宽度和高度
screen_width = login_window.winfo_screenwidth()
screen_height = login_window.winfo_screenheight()
# 设置窗口居中
window_width = 300
window_height = 200
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
login_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
def login():
inputName = name_entry.get()
inputPass = pass_entry.get()
if inputName == userName and inputPass == userPass:
talker.say("恭喜你登录成功!")
talker.runAndWait()
login_window.destroy()
chat_window()
else:
talker.say("账号或密码错误,登录失败")
talker.runAndWait()
name_label = tk.Label(login_window, text="用户名:")
name_label.pack()
name_entry = tk.Entry(login_window)
name_entry.pack()
pass_label = tk.Label(login_window, text="密码:")
pass_label.pack()
pass_entry = tk.Entry(login_window, show="*")
pass_entry.pack()
login_button = tk.Button(login_window, text="登录", command=login)
login_button.pack()
login_window.mainloop()
# 自然语言处理功能
# 启动登录窗口
login_window()

@ -0,0 +1,108 @@
import time
import urllib
import wave
import urllib.parse
import requests
from pyaudio import PyAudio, paInt16
from aip import AipSpeech
import pyttsx3
from AI聊天机器人 import login_window,chat_window
framerate = 16000 # 采样率
num_samples = 2000 # 采样点
channels = 1 # 声道
sampwidth = 2 # 采样宽度2bytes
FILEPATH = 'D:/Tool/test/pythonProject6/myvoices.wav' #该文件目录要存在
#用于接收用户的语音输入, 并生成wav音频文件(wav、pcm、mp3的区别可详情百度)
class Speak():
#将音频数据保存到wav文件之中
def save_wave_file(self, filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b''.join(data))
wf.close()
# 进行语音录制工作
def my_record(self):
pa = PyAudio()
# 打开一个新的音频stream
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = [] # 存放录音数据
t = time.time()
print('正在讲话...')
while time.time() < t + 5: # 设置录音时间(秒)
# 循环read每次read 2000frames
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('讲话结束')
self.save_wave_file(FILEPATH, my_buf) #保存下录音数据
stream.close()
APP_ID = '73927317'
API_KEY = '3jGcj5fLma64CtB3tTEuLcei'
SECRET_KEY = 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG' # 此处填写自己的密钥
"""调用接口, 调用BaiDu AI 接口进行录音、语音识别"""
client = AipSpeech('73927317', '3jGcj5fLma64CtB3tTEuLcei', 'qm8gPCF7DSKpqatx5ZQ8e4OvNLmgdYcG')
class RobotSay():
def __init__(self):
# 初始化语音
self.engine = pyttsx3.init() # 初始化语音库
# 设置语速
self.rate = self.engine.getProperty('rate')
self.engine.setProperty('rate', self.rate - 50)
def say(self, msg):
# 输出语音
self.engine.say(msg) # 合成语音
self.engine.runAndWait()
class ReadWav():
# 读取文件
def get_file_content(self, filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def predict(self):
# 调用百度AI的接口, 识别本地文件
return client.asr(self.get_file_content('D:/Tool/test/pythonProject6/myvoices.wav'), 'wav', 16000, {
'dev_pid': 1537,
})
def talkWithRobot(msg):
url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}'.format(urllib.parse.quote(msg))
html = requests.get(url)
return html.json()["content"]
robotSay = RobotSay()
speak = Speak()
readTalk = ReadWav()
while True:
speak.my_record() #录音
text = readTalk.predict()['result'][0] #调用百度AI接口, 将录音转化为文本信息
print("本人说:", text) #输出文本信息
response_dialogue = talkWithRobot(text) #调用青云客机器人回答文本信息并返回
print("青云客说:", response_dialogue) #输出回答文本信息
robotSay.say(response_dialogue) #播放回答信息
readWav = ReadWav() # 实例化方法
print(readWav.predict())
Loading…
Cancel
Save