How to Add Click‑Triggered Text‑to‑Speech in Vue with speak‑tts
This guide shows how to integrate the speak‑tts library into a Vue component to trigger speech synthesis on button click, covering Chrome’s autoplay restrictions, npm installation, object initialization, button markup, click handler, and a complete working example.
The speak-tts plugin enables a web page to synthesize speech from text. This article demonstrates how to use it in a Vue application so that clicking a button reads a specified string aloud.
Chrome has blocked automatic audio playback since April 2018. The browser only allows audio after a user interaction such as click, double‑click, or touch. Directly calling .play() without interaction throws Uncaught (in promise) DOMException.
Step‑by‑step implementation
Install the package from npm: npm install speak-tts Import the library in the component: import Speech from 'speak-tts' Declare a speech property in the component’s data:
data() {
return {
speech: null,
};
}Initialize the speech object after the component mounts:
mounted() {
this.speechInit();
},
methods: {
speechInit() {
this.speech = new Speech();
this.speech.setLanguage("zh-CN");
this.speech.init().then(() => {});
},Add a button that triggers the speech:
<el-button type="success" @click="speakTtsSpeech">speak-tts语音播报</el-button>Define the click handler to speak the desired text:
speakTtsSpeech() {
this.speech.speak({ text: "公众号:霸道的程序猿" }).then(() => {
console.log("读取成功");
});
},Complete example
<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>With this setup, the button click complies with Chrome’s autoplay policy and successfully reads the specified text aloud.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
