Home > Web Front-end > Vue.js > body text

Detailed step-by-step explanation of how Vue implements voice broadcast (with code)

藏色散人
Release: 2022-11-14 20:29:02
forward
4770 people have browsed it

How does vue implement voice broadcast after clicking a button? Just use this plugin! Let me take you through a detailed understanding of how to use the speak-tts plug-in in Vue to implement voice broadcast after clicking a button. This article is attached with detailed example code. I hope it will be helpful to friends who need it. Welcome to learn!

Detailed step-by-step explanation of how Vue implements voice broadcast (with code)

Use the speak-tts plug-in in Vue to implement voice broadcast (TTS/text-to-speech) after clicking the button

scenario

speak-tts plug-in

https://www.npmjs.com/package/speak-tts (Learning video sharing: vue video tutorial)

Click the button to trigger the voice broadcast and broadcast the specified text content.

Why can’t automatic voice broadcast be implemented?

Since April 2018, the Chrome browser has completely banned the automatic playback function of audio and video in desktop browsers.

Strictly speaking, Chrome does not allow audio to be played before the user triggers the web page.

Not only that, when the page is loaded, the user does not have active interactive behaviors such as click, dbclick, touch, etc.

If you use js to directly call the .play() method, chrome will throw The following error occurred: Uncaught (in promise) DOMException;

Implementation

1. Refer to the official instructions to install dependencies

npm install speak-tts
Copy after login

2. Introduce

import Speech from 'speak-tts'
Copy after login

3 into the page. Declare the speech object

  data() {    return {
      speech: null,
    };
Copy after login

4. Load the page After calling the initialization method

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

5. Add a button to the page

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

6. Call the playback method in the button click event

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

7. Complete sample code


<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>