项目中有类似于美团外卖那种语音提示,如果有人预约,就会有消息提示,但是Chorme浏览器无法自动循环播放,之前在网上各种百度也没找到解决办法,最后经过一番努力,终于实现了这种效果。代码如下:
//这是audio标签
<audio
src="../static/audios/yochima.mp3"//音频路径
muted //静音播放
autoplay//自动播放
loop//循环播放
id="myPlay"
style="display: none"
></audio>
<script>
export default {
data(){
return {
play: false,
t1: 5001,
t2: 6000,
timer: null,
reservationInfoNum :0,//预约消息数量
}
},
mounted() {
let audio = document.getElementById("myPlay");
audio.muted = true; //关闭静音状态
//getResevationInfoNum方法是我的接口
getResevationInfoNum({ storeCode: this.storeCode }).then((res) => {
if (res.code === 0) {
console.log(res);
this.reservationInfoNum = res.data;
this.timer = setInterval(() => {
getResevationInfoNum({ storeCode: this.storeCode }).then((res) => {
if (res.code === 0) {
this.reservationInfoNum = res.data;
if (res.data > 0) {
this.run();//语音播报代码
}
}
});
}, 5000);
}
});
},
methods: {
//语音播报
run() {
let audio = document.getElementById("myPlay");
if (this.play) {
return false;
}
audio.currentTime = 0; //播放音频的起始时间
audio.volume = 1; //音频声音大小
audio.muted = false; //关闭静音状态
this.play = true;
setTimeout(() => {
this.play = false;
audio.muted = true; //播放完毕,开启静音状态
}, this.t2);
},
},
}
</script>
最终实现了,语音播报功能.