1.具体代码实现
<template>
</template>
<script>
export default {
name: 'Test',
data() {
return {
isSpeaking: false // 标记是否正在播放语音
}
},
created() {
this.initWebSocket()
},
destroyed() {
this.websock.close()
},
methods: {
async speak(text) {
if (!this.isSpeaking) { // 如果没有正在播放就进行播放
this.isSpeaking = true; // 标志为正在播放
const utterance = new SpeechSynthesisUtterance(text);
utterance.onend = () => {
this.isSpeaking = false; // 播放结束后置标志为未播放
};
utterance.rate = 0.8;
utterance.voice = speechSynthesis.getVoices()[0];
speechSynthesis.speak(utterance);
} else {
return ''
}
},
// 链接websocket
initWebSocket() {
this.websock = new WebSocket('ws://127.0.0.1:9001/Test')
this.websock.onmessage = this.websocketonmessage
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onclose = this.websocketclose
},
websocketonopen() {
console.log('socket连接成功')
},
websocketonerror() {
this.initWebSocket()
},
websocketonmessage(res) {
const received_msg = JSON.parse(res.data)
const panelData = received_msg.result.location
const resultText = received_msg.result.text
if(panelData===1){
this.speak(resultText)
}else {
return ''
}
},
websocketclose() {
console.log('socket断开链接')
}
}
}
</script>
<style scoped>
</style>
2.WebSocket接口数据结构
{
"result": {
"location": 1,
"text": "语音测试"
}
}