Vue结合WebSocket实现语音播报功能

该代码示例展示了一个Vue组件,使用WebSocket连接服务器并监听消息。当接收到特定位置的数据时,通过WebSpeechAPI播放语音。如果语音正在播放,则不会重复播放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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": "语音测试"
    }
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值