场景
speak-tts插件
实现点击按钮触发语音播报,播报指定的文字内容。
为什么不能实现自动语音播报。
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>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/136094.html