vue3中使用speak-tts插件进行语音播报

vue3中使用speak-tts插件进行语音播报

我们需要先下载 speak-tts 插件

npm i speak-tts

官方地址包含更多配置等信息

下面将简单模拟一下如何在vue组件中使用

template

<h1 @click="voice">{{ $t('home.title') }}h1>

js

//先引入下载好的插件
import Speech from 'speak-tts';
//引入ele - 可忽略
import { ElMessageBox, ElNotification } from 'element-plus';

//定义一个源
const speech = new Speech();
//判断用户当前浏览器是否支持语音播报
if (speech.hasBrowserSupport()) {
  ElNotification({
    title: '语音提示',
    message: '支持语音合成',
    type: 'success',
    showClose: false,
  });
} else {
  ElNotification({
    title: '语音提示',
    message: '不支持语音合成',
    type: 'error',
    showClose: false,
  });
}
//初始化语音插件 - init内可以全部为空 - 自定义
speech
  .init({
    volume: 1, // 音量
    lang: 'zh-CN', // 语言
    rate: 1, // 语速
    pitch: 1, // 音调
    splitSentences: true, // 在句子结束时暂停
    listeners: {
      // 事件
      onvoiceschanged: voices => {
        // console.log('事件声音已更改', voices);
      },
    },
  })
  .then(data => {
    console.log('语音已准备好,声音可用', data);
  })
  .catch(e => {
    console.error('初始化时发生错误 : ', e);
  });
  //语音播报按钮
  function voice() {
  speech
    .speak({
      text: t('home.title'), //这里使用文字或者i18n 都可以 看自己需求
    })
    .then(() => {
      console.log('Success !');
    })
    .catch(e => {
      console.error('An error occurred :', e);
    });
}

以上就是简单的语音播报案例,更多配置,包括 语音暂停,开始,终止,速率,音量,声音… 等可以去官方下面看自己需要的配置

vue3中使用speak-tts插件进行语音播报_第1张图片
等…

你可能感兴趣的:(javascript,vue)