在页面中需要加个音频文件进行模仿。

在vue项目中,先定义好audio标签

<audio :src="guideVoice" ref="guideVoice"></audio>

方法一

然后设置guideVoice,值之后,监听canplaythrough事件,看是否可以播放,然后控制播放

this.$refs.guideVoice.addEventListener("canplaythrough", () => {
this.$refs.guideVoice.play();
}, false);

方法二

一的方法有问题,在重复播放的时候就不播放了,我们使用这种方法


this.$refs.guideVoice.load();
this.$refs.guideVoice.play();

要先于这个渲染周期设置好播放的src

在电脑上测试可以,但是在iphonex手机上还有问题,经查是ios上面必须是用户点击触发之后才可以,不能自动播放

参考文章: ​​Safari中js代码出错:Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context​