(编辑:jimmy 日期: 2024/12/27 浏览:2)
框架相关
Demo采用Mpvue框架,后端的WebSocket采用Node.js,文件服务器直接使用的微信小程序的云开发的存储。
储备知识
Node.js端WebScoket实现
// 基于WS插件 // 引入ws插件 var WebSocketServer = require("ws").Server; // 实例化WebSocket var wss = new WebSocketServer({ port: 9090 }); // 初始化客户端数组 var clients = []; // 建立链接监听 wss.on('connection', function (ws) { clients.push(ws); ws.on("message", function (message) { clients.forEach(function (ws1) { if (ws1 !== ws) { ws1.send(message) } }) }) }) // 建立链接关闭监听 ws.on("close", function (message) { clients = clients.filter(function (ws1) { return ws1 !== ws }) })
小程序端实现
html
<div> <button @click="palyAudio(value)" v-for="(value,index) in chatContent" :key="index">)))))</button> <button class="botom-button" @touchstart="startRecord" @touchend="stopRecord">输入语音</button> </div>
js
export default { data() { return { // 存储聊天记录 chatContent: [], // 录音控制器 recorderManager: null, // 音频控制器 innerAudioContext: null }; }, methods: { // 按下按钮开始录音 startRecord() { this.recorderManager.start({ format: "mp3" }); }, // 松开按钮停止录音 stopRecord() { this.recorderManager.stop(); }, // 播放录音 palyAudio(value) { this.innerAudioContext.src = value; this.innerAudioContext.play(); } }, created() { this.recorderManager = wx.getRecorderManager(); this.innerAudioContext = wx.createInnerAudioContext(); // 监听录音开始 this.recorderManager.onStart(res => { console.log("recordStart"); }); // 监听录音结束 this.recorderManager.onStop(res => { const audioName = new Date().getTime() + ".mp3"; // 上传录音文件 wx.cloud.uploadFile({ cloudPath: audioName, filePath: res.tempFilePath, success: upload => { this.chatContent.push(upload.fileID); // 通过websocket传递录音连接 wx.sendSocketMessage({ data: upload.fileID }); } }); }); // 建立websocket链接 wx.connectSocket({ url: "ws://yoursiteandeport", success: res => { console.log("success", res); }, fail: err => { console.log("error", err); } }); // websocket消息监听 wx.onSocketMessage(data => { console.log(data); this.chatContent.push(data.data); }); } };
结论