利用浏览器语音播放api功能,在vue项目中调用api实现语音播报。
在mounted生命周期函数中获取浏览器的SpeechSynthesis API
data() {
return {
speech: null,
};
},
mounted() {
if ("SpeechSynthesisUtterance" in window) {
this.speech = window.speechSynthesis;
} else {
// eslint-disable-next-line no-console
console.log("不支持语音播放API");
}
},
methods 中方法
methods: {
//调用业务
handleConfirm() {
let t = `请 1号 到前台取餐`;
this.speechInit(`${t}`);
},
//初始化
speechInit(text) {
let utterThis = new SpeechSynthesisUtterance(text);
utterThis.pitch = 1; // 音高
utterThis.rate = 1; // 语速
utterThis.volume = 1; // 音量
utterThis.lang = "zh-CN"; // 播报语言
this.speech.speak(utterThis);
},
}
通过HBuilder X在打包成apk安装包时,需要在manifest.json文件中添加对应的权限设置。