场景

speak-tts插件

speak-tts - npm

实现点击按钮触发语音播报,播报指定的文字内容。

为什么不能实现自动语音播报。

chrome浏览器在18年4月起,就在桌面浏览器全面禁止了音视频的自动播放功能。

严格地来说,是Chrome不允许在用户对网页进行触发之前播放音频。

不光是这样,在页面加载完毕的情况下,用户没有click、dbclick、touch等主动交互行为,

使用js直接调用.play() 方法的话,chrome都会抛出如下错误:Uncaught (in promise) DOMException;

注:

博客:
BADAO_LIUMANG_QIZHI的博客_霸道流氓气质_CSDN博客-C#,SpringBoot,架构之路领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、参考官方说明安装依赖

npm install speak-tts

2、在页面中引入

import Speech from 'speak-tts'

3、声明speech对象

  data() {
    return {
      speech: null,
    };

4、页面加载完调用初始化方法

  mounted() {
    this.speechInit();
  },
  methods: {
    speechInit() {
      this.speech = new Speech();
      this.speech.setLanguage("zh-CN");
      this.speech.init().then(() => {});
    },

5、页面添加按钮

<el-button type="success" @click="speakTtsSpeech">speak-tts语音播报</el-button>

6、按钮点击事件中调用播放方法

    speakTtsSpeech() {
      this.speech.speak({ text: "公众号:霸道的程序猿" }).then(() => {
        console.log("读取成功");
      });
    },

7、完整示例代码

<template>
  <el-button type="success" @click="speakTtsSpeech">speak-tts语音播报</el-button>
</template>
<script>
import Speech from "speak-tts"; // es6
export default {
  name: "SpeechDemo",
  data() {
    return {
      speech: null,
    };
  },
  mounted() {
    this.speechInit();
  },
  methods: {
    speakTtsSpeech() {
      this.speech.speak({ text: "公众号:霸道的程序猿" }).then(() => {
        console.log("读取成功");
      });
    },
    speechInit() {
      this.speech = new Speech();
      this.speech.setLanguage("zh-CN");
      this.speech.init().then(() => {});
    },
  },
};
</script>

<style scoped>
</style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐