vue 前端JS实现文字转语音功能
上代码
//data 中定义判断IE的方法isIe():() => {if(!!window.ActiveXObject || "ActiveXObject " in window){return true}else{return false}}// methodslet msg = 'hello world'if(this.isIe()){let voiceObj = new ActiveXObject("Sapi.SpVoice")voiceObj.Rate = -1 // 语速voiceObj.Volume = 60 // 音量voiceObj.Speak(msg,1)}else{let speakMsg = new SpeechSynthesisUtterance(msg)speakMsg.rate = 1 // 语速speakMsg.pitch = 1.5 // 音量window.speechSynthesis.speak(speakMsg)}
/*循环播放语音第一种: 不点击触发下列方法,需要后台通过Websocket推送消息,前端参考HTML5 WebSocket设置接收后台消息并触发下面方法第二种: 通过事件触发第三种: 一进入页面自动播放,将下列方法放到mounted()或者created()中即可*/let timertimer = setInterval(() => {let msg = 'hello world'if(this.isIe()){let voiceObj = new ActiveXObject("Sapi.SpVoice")voiceObj.Rate = -1 // 语速voiceObj.Volume = 60 // 音量voiceObj.Speak(msg,1)}else{let speakMsg = new SpeechSynthesisUtterance(msg)speakMsg.rate = 1 // 语速speakMsg.pitch = 1.5 // 音量window.speechSynthesis.speak(speakMsg)}}, 延时的时间)setTimeOut(() => {// 一段时间后清除定时器clearInterval(timer)}, 一段时间)// 如果需要点击循环再次点击移除可手动添加移除定时器