当前位置: 首页 > article >正文

青云客-网页端语音机器人

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文件,即可运行网页!

4、运行效果:


http://www.kler.cn/a/461941.html

相关文章:

  • 每天40分玩转Django:Django Celery
  • C++编程库与框架实战——ZeroMQ消息队列
  • 在虚幻引擎4(UE4)中使用蓝图的详细教程
  • Unity2022接入Google广告与支付SDK、导出工程到Android Studio使用JDK17进行打包完整流程与过程中的相关错误及处理经验总结
  • lec5-传输层原理与技术
  • AWS K8s 部署架构
  • 笔上云世界微服务版
  • LabVIEW声波谐振管自动化测量系统
  • 33. 简易内存池
  • 使用jest-axe为你的前端项目自动化测试
  • 免费又开源:企业级物联网平台的新选择 ThingsPanel
  • 如何使用 OpenCV 扫描图像、查找表和时间测量
  • 数据结构与算法之查找
  • Python大数据可视化:基于大数据技术的共享单车数据分析与辅助管理系统_flask+hadoop+spider
  • C++ 内存
  • 混合合并两个pdf文件
  • FastAPI 集成 MySQL 和 Redis:模型与模式生成实践
  • ARM 架构--通用寄存器状态寄存器控制寄存器特殊用途寄存器
  • 【《python爬虫入门教程11--重剑无峰168》】
  • 算法进阶:贪心算法
  • 自学记录鸿蒙API 13:PreviewKit从文件预览到应用开发
  • 详细讲一下React中的路由React Router
  • [离线数仓] 总结
  • 7.无穷级数练习
  • 使用 Python -m build打包 Python 项目:详解过程与细节
  • 为何DeepSeek V3模型为自己是ChatGPT?