失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > vue3实现语音播放功能

vue3实现语音播放功能

时间:2020-11-07 04:02:47

相关推荐

vue3实现语音播放功能

onMounted(() => {var lockReconnect = false; //避免ws重复连接var ws = null; // 判断当前浏览器是否支持WebSocketvar wsUrl = "ws:121.41.170.54:2346";createWebSocket(wsUrl); //连接wsfunction createWebSocket(url) {try {if ('WebSocket' in window) {ws = new WebSocket(url);}initEventHandle();} catch (e) {// reconnect(url);console.log(e);}}function initEventHandle() {ws.onclose = function() {reconnect(wsUrl);console.log("llws连接关闭!" + new Date().toLocaleString());};ws.onerror = function() {reconnect(wsUrl);console.log("llws连接错误!");};ws.onopen = function() {heartCheck.reset().start(); //心跳检测重置console.log("llws连接成功!" + new Date().toLocaleString());};ws.onmessage = function(event) { //如果获取到消息,心跳检测重置heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的if (event.data != 'pong') {console.log(event.data);let data = JSON.parse(event.data);var name = "昨日计划未完成人员名单如下:";if (data.names.length > 0) {for (var i = 0; i < data.names.length; i++) {name += data.names[i].name + ','}}const synth = window.speechSynthesis;const msg = new SpeechSynthesisUtterance();msg.text = name; // 文字内容msg.lang = "zh-CN"; // 使用的语言:中文msg.volume = 1; // 声音音量:0-1msg.rate = 0.5; // 语速:0-10msg.pitch = 1; // 音高:0-1synth.speak(msg); // 播放}};}// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function() {ws.close();}function reconnect(url) {if (lockReconnect) return;lockReconnect = true;setTimeout(function() { //没连接上会一直重连,设置延迟避免请求过多createWebSocket(url);lockReconnect = false;}, 2000);}//心跳检测var heartCheck = {timeout: 5000, //5秒发一次心跳timeoutObj: null,serverTimeoutObj: null,reset: function() {clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);return this;},start: function() {var self = this;this.timeoutObj = setTimeout(function() {//这里发送一个心跳,后端收到后,返回一个心跳消息,//onmessage拿到返回的心跳就说明连接正常ws.send("ping");// console.log("ping!")self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置,说明后端主动断开了ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次}, self.timeout)}, this.timeout)}}});

如果觉得《vue3实现语音播放功能》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。