方法一:通过显示“需要播放音频”弹窗,进行交互之后播放。
<audio ref="audioRef">
<source src="./mp3/tishi.mp3" />
</audio>
<script setup>
import { ref } from 'vue'
let audioRef = ref(null)
onMounted(() => {
if (window.performance.navigation.type === 1) {
audioClick()
} else {
handelShow()
}
})
const audioClick = () => {
let startPlayPromise = audioRef.value.play()
if (startPlayPromise !== undefined) {
startPlayPromise.catch(error => {
if (error.name === 'NotAllowedError') {
ElMessageBox.alert('当前正在自动播放音频', '提示', {
confirmButtonText: '确认',
callback: () => {
audioRef.value.play()
},
})
}
})
}
}
const handelShow = () => {
audioRef.value.play()
}
</script>
方法二:通过监听页面点击事件,页面有交互之后播放。
data() {
return {
initIntervalPlay:null,
firstPlayVid: true,
}
},
mounted() {
const audio =document.getElementById("videoSound");
let startPlayPromise = audio.play();
if (startPlayPromise !== undefined) {
startPlayPromise
.catch((error) => {
document.removeEventListener('click', this.playHandle)
document.addEventListener('click', this.playHandle)
})
.then(() => {
this.intervalPlay()
});
}
}
playHandle() {
if (this.firstPlayVid) {
document.getElementById("videoSound").play()
this.intervalPlay()
this.firstPlayVid = false
}
},
intervalPlay(){
if (this.initIntervalPlay) {
window.clearInterval(this.initIntervalPlay)
}
this.initIntervalPlay = setInterval(() => {
document.getElementById("videoSound").play()
}, 5000)
}