vue项目实现文字语音播报

<template>
  <div>
    <input v-model="textToSpeech" placeholder="输入文字">
    <button @click="speak">语音播报</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      textToSpeech: '', // 用于存储要语音播报的文本
      speech: null // 用于存储语音合成对象
    };
  },
  methods: {
    speak() {
      // 检查浏览器是否支持Web Speech API
      if ('speechSynthesis' in window) {
        // 创建一个新的语音合成对象
        this.speech = new SpeechSynthesisUtterance(this.textToSpeech);
        // 设置语音参数(可选)
        this.speech.lang = 'zh-CN'; // 设置语言为中文
        this.speech.rate = 1; // 设置语速
        this.speech.pitch = 1; // 设置音高
        this.speech.volume = 1; // 设置音量
        // 将语音合成对象添加到队列并开始播放
        window.speechSynthesis.speak(this.speech);
      } else {
        alert('您的浏览器不支持语音合成功能');
      }
    }
  }
};
</script>