2025.06.19今天我把文字转语音的方法封装成一个方法,代码如下:

一、text_switch_speak.js

export function text_switch_speak(text)  {
    return new Promise(resolve => {
        const msg = new SpeechSynthesisUtterance(text);
        msg.lang = 'zh-CN';//语言
        msg.rate = 0.8;//语速
        msg.onend = () => {//结束播放方法
            window.speechSynthesis.cancel();//关闭所有语音
            if (!window.speechSynthesis.paused) {//判断是否为暂停状态,如果不是就在两秒后进行下一个语音播放
                // 语音结束后等待指定时间再继续
                setTimeout(() => {
                    resolve();
                }, 2000);
            }
        };
        msg.onresume = ()=>{//继续播放方法
            window.speechSynthesis.resume();//把对象置为一个非暂停状态:如果已经暂停了则继续
        }
        window.speechSynthesis.speak(msg);
    });
}

二、其他页面引用:

<template>
  <div>
     <el-button @click="open()">打开</el-button>
     <el-button @click="pause_click()">暂停</el-button>
     <el-button @click="continue_click()">继续</el-button>
     <el-button @click="close()">关闭</el-button>
  </div>
</template>

<script>
export default{
import {text_switch_speak} '@/utils/text_switch_speak.js'
    data(){
     return{


      }
   } ,
    await created(){

    },
    methods:{
      //打开
      await open(){
          await text_switch_speak('小朋友,你是否有很多问号?');

          await text_switch_speak('Hello,world');
      },
      //暂停
      pause_click(){
          window.speechSynthesis.pause();//暂停播放
      },
      //继续
      continue_click(){
          window.speechSynthesis.resume();//继续播放
      },
      //关闭
      close(){
          window.speechSynthesis.cancel();//关闭播放
      },
   }
}
</script>

HTML5语音合成技术:SpeechSynthesis与Utterance详解-CSDN博客

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐