Home > front end >  Video not playing after setting source in javascript
Video not playing after setting source in javascript

Time:10-03

I am trying to make one out of two videos play randomly without any javascript frameworks but the autoplay does not work.

function event() {
  let oldnovid = novid;
  let a = Math.round(Math.random() * 100);
  let sauce = document.getElementById("sauce");
  if (a <= 20) {
    document.getElementById("bgvid").mute = true;
    sauce.setAttribute("src", "sauce/bg.mp4");
    novid = 300000;
  } else if (a >= 80) {
    document.getElementById("bgvid").mute = true;
    sauce.setAttribute("src", "sauce/bg2.mp4");
    novid = 207000;
  } else {
    novid = 1000;
  }
  document.getElementById("bgvid").play();
  document.getElementById("bgvid").mute = false;
  console.log(a);
  clearInterval(id);
  id = setInterval(event, novid);
}

event();
<video id="bgvid" autoplay="" muted="true">
  <source src="" id="sauce" type="video/mp4">
</video>

CodePudding user response:

I think you should do

document.getElementById("bgvid").autoplay = true
document.getElementById("bgvid").load()

and remove autoplay=""

Instead of

document.getElementById("bgvid").play()

So it will automatically play. Not sure, but you should have a try

CodePudding user response:

function event() {
    let oldnovid = novid
    let a = Math.round(Math.random() * 100);
    let sauce = document.getElementById("sauce")
    if (a <= 20) {
        sauce.setAttribute("src", "sauce/bg.mp4")
        clearInterval(id)
        id = setInterval(event, 30000);

        document.getElementById("bgvid").autoplay = true;
        document.getElementById("bgvid").muted = false;
        document.getElementById("bgvid").load();
        let playAttempt = setInterval(() => {
            document.getElementById("bgvid")
                .play()
                .then(() => {
                    clearInterval(playAttempt);
                })
        }, 50)
    } else if (a >= 80) {
        sauce.setAttribute("src", "sauce/bg2.mp4")
        clearInterval(id)
        id = setInterval(event, 200400);

        document.getElementById("bgvid").autoplay = true;
        document.getElementById("bgvid").muted = false;
        document.getElementById("bgvid").load();
        let playAttempt = setInterval(() => {
            document.getElementById("bgvid")
                .play()
                .then(() => {
                    clearInterval(playAttempt);
                })
        }, 50)
    } else {
        clearInterval(id)
        id = setInterval(event, 1000);
    }

    console.log(a);

}

This worked in the end. after the user did something.

  • Related