granby
granby

Reputation: 90

JavaScript snippet to make visual changes based on audio playback

I'm trying to write some JS that will change a square from blue to yellow if the audio has played for a second or more. Currently, no change seems to happen at all. This is the first bit of JS that I've tried writing by myself, so if anyone has a tip that would be awesome.

// sound from https://www.w3schools.com/tags/horse.ogg

// when one second or more of the audio is played, change the square from blue to yellow

window.onload = function() {

  function changeColor() {
    var timedChange = document.getElementById("audioPlayer").currentTime;
    if (timedChange >= 1) {
      document.getElementById("yellow").style.display = "block";
    } else {
      document.getElementById("yellow").style.display = "none";
    }
  };
}
#blue {
  width: 200px;
  height: 200px;
  background-color: blue;
}

#yellow {
  width: 200px;
  height: 200px;
  background-color: yellow;
  position: absolute;
  top: 8px;
  display: none;
}

#audioPlayer {
  position: absolute;
  right: 500px;
  top: 10px;
}
<div id="blue"></div>

<div id="yellow"></div>

<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" onclick="changeColor()" controls>
</audio>

Upvotes: 0

Views: 62

Answers (2)

dev village
dev village

Reputation: 73

const audio = document.getElementById("audioPlayer");

// show yellow square after 1sec (1000 millisec) of audio playback
audio.onplay = () => {
  setTimeout( () => {
    document.getElementById("yellow").style.display = "block";
  }, 1000);
};

// hide the yellow square immedeately when the audio stops
audio.onpause = () => { 
  document.getElementById("yellow").style.display = "none"; 
};
#blue {
  width: 200px;
  height: 200px;
  background-color: blue;
}

#yellow {
  width: 200px;
  height: 200px;
  background-color: yellow;
  position: absolute;
  top: 8px;
  display: none;
}

#audioPlayer {
  position: absolute;
  right: 500px;
  top: 10px;
}
<div id="blue"></div>

<div id="yellow"></div>

<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" controls>
</audio>

Upvotes: 1

Three problems:

  1. That's not the right syntax to declare a function at top-level. Instead of timedChange: function(), either do timedChange = function() or function timedChange().
  2. You're not calling the function anywhere, so it never will run.
  3. Don't use the same name for a variable as you do for your function. In JavaScript, they're in the same namespace.

Upvotes: 0

Related Questions