青云客-网页端语音机器人
1、青云客官网:
青云客智能聊天机器人API
2、完整代码:
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语音聊天机器人</title>
<style>
/* 样式与之前一致 */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#chatApp {
width: 100%;
max-width: 500px;
height: 80%;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
border-radius: 10px;
display: flex;
flex-direction: column;
overflow: hidden;
}
#chatHeader {
background-color: #4CAF50;
color: white;
padding: 15px;
text-align: center;
font-size: 20px;
font-weight: bold;
}
#chatBox {
flex: 1;
overflow-y: auto;
padding: 10px;
background-color: #f9f9f9;
}
.message {
margin: 10px 0;
display: flex;
flex-wrap: wrap;
}
.message.user {
justify-content: flex-end;
}
.message.bot {
justify-content: flex-start;
}
.message span {
max-width: 70%;
padding: 10px;
border-radius: 10px;
display: inline-block;
}
.message.user span {
background-color: #4CAF50;
color: white;
}
.message.bot span {
background-color: #e0e0e0;
color: black;
}
#chatControls {
display: flex;
align-items: center;
padding: 10px;
background-color: #f1f1f1;
border-top: 1px solid #ddd;
}
#userInput {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
margin-right: 10px;
}
#sendButton,
#voiceButton {
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#sendButton:hover,
#voiceButton:hover {
background-color: #45a049;
}
#voiceButton {
margin-left: 10px;
}
</style>
</head>
<body>
<div id="chatApp">
<div id="chatHeader">语音聊天机器人</div>
<div id="chatBox"></div>
<div id="chatControls">
<input type="text" id="userInput" placeholder="输入消息..." autocomplete="off">
<button id="sendButton" onclick="sendMessage()">发送</button>
<button id="voiceButton" onclick="toggleSpeechRecognition()">🎤 开始语音</button>
</div>
</div>
<script>
let recognition = null; // 语音识别对象
let isListening = false; // 标记语音识别状态
// 自动滚动到底部
function scrollToBottom() {
const chatBox = document.getElementById("chatBox");
chatBox.scrollTop = chatBox.scrollHeight;
}
// 语音合成(Text-to-Speech)
function speakText(text) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = "zh-CN";
speechSynthesis.speak(utterance);
}
// 启动或停止语音识别
function toggleSpeechRecognition() {
if (isListening) {
stopSpeechRecognition();
} else {
startSpeechRecognition();
}
}
// 开始语音识别
function startSpeechRecognition() {
if (!recognition) {
recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = "zh-CN";
recognition.onstart = () => {
console.log("语音识别已启动...");
document.getElementById("voiceButton").textContent = "🛑 停止语音";
};
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
console.log("识别结果:", transcript);
// 将识别到的文本显示到输入框并发送
document.getElementById("userInput").value = transcript;
sendMessage();
};
recognition.onerror = (event) => {
console.error("语音识别错误:", event.error);
alert("语音识别失败,请重试。");
};
recognition.onend = () => {
isListening = false;
document.getElementById("voiceButton").textContent = "🎤 开始语音";
console.log("语音识别已结束");
};
}
recognition.start();
isListening = true;
}
// 停止语音识别
function stopSpeechRecognition() {
if (recognition && isListening) {
recognition.stop();
isListening = false;
document.getElementById("voiceButton").textContent = "🎤 开始语音";
console.log("语音识别已手动停止");
}
}
async function sendMessage() {
const userMessage = document.getElementById("userInput").value.trim();
if (!userMessage) return;
// 显示用户消息
const chatBox = document.getElementById("chatBox");
const userMessageElem = document.createElement("div");
userMessageElem.className = "message user";
userMessageElem.innerHTML = `<span>${userMessage}</span>`;
chatBox.appendChild(userMessageElem);
// 滚动到底部
scrollToBottom();
// 发送消息到代理服务器
try {
const response = await fetch(`http://localhost:5000/proxy?key=free&appid=0&msg=${encodeURIComponent(userMessage)}`);
if (!response.ok) {
throw new Error(`HTTP 错误: ${response.status}`);
}
const data = await response.json();
console.log("收到响应:", data);
// 显示机器人的回复
const botMessageElem = document.createElement("div");
botMessageElem.className = "message bot";
botMessageElem.innerHTML = `<span>${data.content || "我无法处理您的请求。"}</span>`;
chatBox.appendChild(botMessageElem);
// 语音合成机器人的回复
speakText(data.content || "我无法处理您的请求。");
} catch (error) {
console.error("请求失败:", error);
const botMessageElem = document.createElement("div");
botMessageElem.className = "message bot";
botMessageElem.innerHTML = `<span>请求出错,请稍后再试。</span>`;
chatBox.appendChild(botMessageElem);
}
// 清空输入框并滚动到底部
document.getElementById("userInput").value = "";
scrollToBottom();
}
</script>
</body>
</html>
proxy_server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests
app = Flask(__name__)
CORS(app) # 启用 CORS 支持
@app.route('/proxy', methods=['GET'])
def proxy():
api_url = "http://api.qingyunke.com/api.php"
params = {
"key": request.args.get("key", "free"),
"appid": request.args.get("appid", "0"),
"msg": request.args.get("msg", "")
}
print("请求参数:", params) # 打印调试信息
try:
response = requests.get(api_url, params=params)
print("API 响应:", response.text) # 打印 API 响应
return jsonify(response.json())
except requests.RequestException as e:
print("请求失败:", e) # 打印错误信息
return jsonify({"result": 1, "content": f"代理服务器出错: {str(e)}"})
if __name__ == '__main__':
app.run(port=5000)
3、运行方式:
在终端下输入
python .\proxy_server.py
然后点击html文件,即可运行网页!