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!
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
2. Introduce
import Speech from 'speak-tts'
3 into the page. Declare the speech object
data() { return { speech: null, };
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(() => {}); },
5. Add a button to the page
<el-button type="success" @click="speakTtsSpeech">speak-tts语音播报</el-button>
6. Call the playback method in the button click event
speakTtsSpeech() { this.speech.speak({ text: "公众号:霸道的程序猿" }).then(() => { console.log("读取成功"); }); },
7. Complete sample code
<el-button type="success" @click="speakTtsSpeech">speak-tts语音播报</el-button> <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>Copy after login
The above is the detailed content of Detailed step-by-step explanation of how Vue implements voice broadcast (with code). For more information, please follow other related articles on the PHP Chinese website!