Chrome video autoplay

前端 未结 6 1594
鱼传尺愫
鱼传尺愫 2021-01-19 23:06

Following Chrome & Firefox\'s recent update autoplay videos are no longer supported - I\'ve tried to add some code to play this on startup but it doesn\'t seem to work?<

6条回答
  •  隐瞒了意图╮
    2021-01-19 23:33

    I've found a good way how to autoplay the video and avoid a js error in console.

    const myVideo = document.getElementById('my-video');
    
    // Not all browsers return promise from .play().
    const playPromise = myVideo.play() || Promise.reject('');
    playPromise.then(() => {
      // Video could be autoplayed, do nothing.
    }).catch(err => {
      // Video couldn't be autoplayed because of autoplay policy. Mute it and play.
      myVideo.muted = true;
      myVideo.play();
    });

    This code tries to start autoplay with sound, and if it's not possible then it will mute the video and autoplay the video without sound. I think it's an optimal way and prevents JS errors.

提交回复
热议问题