[HTML 5] Autoplay video

Normal browser has restiction that doesn't allow you automaticlly play the video, unless your site has high Media Enagement index (MEI).

There are 2 way to resolve this problem.

1. Click and Play

async function play() {
    try {
        await vdo.play();
        vdoContainer.style.display = 'none'
        playBtn.removeEventListener('click', play)
    } catch(err) {
        vdoContainer.style.display = 'flex'
        playBtn.addEventListener('click', play)
    }
}

2. Mute the sound and Play

async function play() {
    vdo.muted = true
    vdo.play()
    const ctx = new AudioContext()
    const canAutoPlay = ctx.state === 'running'
    ctx.close()
    if (canAutoPlay) {
        vdo.muted = false
        vdoContainer.style.display = 'none'
        muteBtn.removeEventListener('click', play)
    } else {
        vdoContainer.style.display = 'flex'
        muteBtn.addEventListener('click', play)
    }
}

 

posted @ 2024-08-25 20:02  Zhentiw  阅读(8)  评论(0编辑  收藏  举报