效果

Vue2代码
<template>
<div class="box">
<input type="text" name="text" id="text" v-model="text" />
<button @click="playVoice">播放语音</button>
<button @click="pauseVoice" v-if="status === '开始播放'">暂停播放</button>
<button @click="resumeVoice" v-if="status === '暂停播放'">继续播放</button>
<button @click="stopVoice">停止播放</button>
<div>播放状态:{{ status }}</div>
</div>
</template>
<script>
const synth = window.speechSynthesis;
const msg = new window.SpeechSynthesisUtterance();
export default {
data() {
return {
text: "",
status: ""
};
},
mounted() {
msg.onstart = e => {
this.status = "开始播放";
};
msg.onend = e => {
this.status = "结束播放";
};
msg.onpause = e => {
this.status = "暂停播放";
};
},
destroyed() {
this.stopVoice();
},
methods: {
playVoice() {
this.handleSpeak();
},
pauseVoice() {
this.handlePause();
},
resumeVoice() {
this.handleResume();
},
stopVoice() {
this.handleStop();
},
handleSpeak() {
if (!this.text) return alert("请输入文本!");
msg.text = this.text;
msg.lang = "zh-CN";
msg.volume = 1;
msg.rate = 1;
msg.pitch = 1;
synth.speak(msg);
},
handleStop(e) {
synth.cancel(msg);
},
handlePause(e) {
synth.pause(msg);
},
handleResume(e) {
synth.resume(msg);
}
}
};
</script>