Vue uses window.speechSynthesis to realize text-to-speech

Vue uses window.speechSynthesis to realize text-to-speech

For other uses of window.speechSynthesis, you can check relevant information by yourself

<template>
  <div style="text-align: center;">
    <el-row>
      <el-radio v-model="id" :label="item.id" v-for="(item,index) in Voices" :key="index" @click.native="playVoice(item,$event)" >{
    
    {
    
    item.name}}</el-radio>
    </el-row>
    <el-row>
      <span>音量:</span> <el-input-number size="mini" v-model="data.volume" :min="1" :max="10"></el-input-number> <span>  </span>
      <span>语速:</span> <el-input-number size="mini" v-model="data.rate" :min="1" :max="10"></el-input-number> <span>  </span>
      <span>音高:</span> <el-input-number size="mini" v-model="data.pitch" :min="1" :max="10"></el-input-number>
    </el-row>
  </div>
</template>
<script>
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();

export default {
    
    
  name: "tts",
  props:{
    
    
    // 文本
    text:{
    
    
      type: String,
      default: '测试语音文本'
    }
  },
  data() {
    
    
    return {
    
    
      id : "1",
      Voices: [
        {
    
    
          id : "1",
          name: "普通话",
          lang: "zh-CN"
        },
        {
    
    
          id : "2",
          name: "粤语",
          lang: "zh-HK"
        },
        {
    
    
          id : "3",
          name: "国语",
          lang: "zh-TW"
        },
        {
    
    
          id : "4",
          name: "Sandy(en)",
          lang: "en-GB"
        },
        {
    
    
          id : "5",
          name: "Shelley(en)",
          lang: "en-GB"
        }
      ],
      data:{
    
    
        // 声音音量
        volume: 1,
        // 语速
        rate: 1,
        // 音高
        pitch: 1,
      }
    };
  },
  created() {
    
    
  },
  methods: {
    
    
    playVoice(vale,e) {
    
    
      // 因为原生click事件会执行两次,第一次在label标签上,第二次在input标签上,故此处理
      if (e.target.tagName === 'INPUT') return;
      msg.lang = vale.lang;
      msg.volume = this.data.volume;
      msg.rate = this.data.rate;
      msg.pitch = this.data.pitch;
      this.handleSpeak(this.text);
    },
    // 语音播报的函数
    handleSpeak(text) {
    
    
      // 文字内容
      msg.text = text;
      // 播放
      synth.speak(msg);
    },

    // 语音停止
    handleStop(e) {
    
    
      msg.text = e;
      msg.lang = "zh-CN";
      synth.cancel(msg);
    },

    //文字转语音js
    textToVoice() {
    
    
      this.speech = new SpeechSynthesisUtterance();
      let speech = this.speech;
      speech.text = "测试文字";
      speech.pitch = 1;// 设置话语的音调(0-2 默认1,值越大越尖锐,越低越低沉)
      speech.rate = 0.9; // 设置说话的速度(0.1-10 默认1,值越大语速越快,越小语速越慢)
      speech.volume = 10;// 设置说话的音量
      speech.lang = 'zh-CN'; // 设置播放语言
      speechSynthesis.speak(speech);
    },

  }
};
</script>

<style >

</style>

Guess you like

Origin blog.csdn.net/god_sword_/article/details/131878640
Recommended