const audio = ref(new Audio())
const voicePath = ref('')const playVoice = () => {// 外部链接//voicePath.value = `https://mp3在线地址`// 本地链接voicePath.value = new URL('@/assets/本地mp3文件', import.meta.url).hrefnextTick(() => {// 从头开始audio.value.currentTime = 0// 播放audio.value?.play()})
}
<audio ref="audio" controls hidden="true" :src="voicePath"/>
报错:Error: Uncaught (in promise) DOMException: play() failed
使用 autoplay 标签和主动调用 play 方法`document.querySelector('video').play()`都会提示此错误
在vue3中实测只需点击页面内 程序才能自动调用播放
问题在于 Chrome 的避免自动播放视屏政策:传送门 - Autoplay policy in Chrome
根据 Chrome 的规则,要想使用autoplay自动播放只能加上 muted
静音属性就允许自动播放了
<video src="sample.mp4" autoplay muted></video>
js监听初次点击后播放:
<video src="sample.mp4" controls autoplay></video><script>const video = document.querySelector('video');// auto play when script loadedvideo.play().then(() => {console.log(`autoplay well`);}).catch((e) => {console.log(`autoplay fail, wait for first click`);if (e instanceof DOMException) {// play before user intersactconst autoPlayAfterAnyClick = () => {video.play();document.removeEventListener('click', autoPlayAfterAnyClick);};document.addEventListener('click', autoPlayAfterAnyClick);throw e;} else {// or rethrowthrow e;}});
</script>