小程序实现简单语音聊天的示例代码
框架相关
Demo采用Mpvue框架,后端的WebSocket采用Node.js,文件服务器直接使用的微信小程序的云开发的存储。
储备知识
- 微信小程序录音控制器:recorderManager。
- 微信小程序音频控制器:innerAudioContext。
- 微信小程序WebSocket。
Node.js端WebScoket实现
//基于WS插件
//引入ws插件
varWebSocketServer=require("ws").Server;
//实例化WebSocket
varwss=newWebSocketServer({port:9090});
//初始化客户端数组
varclients=[];
//建立链接监听
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){
returnws1!==ws
})
})
小程序端实现
html
输入语音
js
exportdefault{
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=>{
constaudioName=newDate().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);
});
}
};
结论
- 主要通过WebSocket完成实时通讯
- 通过微信小程序提供的API完成语音的录入和输出
- 通过文件服务器上传语音文件
到此这篇关于小程序实现简单语音聊天的示例代码的文章就介绍到这了,更多相关小程序语音聊天内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!