简体   繁体   中英

Need video to mute/unmute on keypress (No Button)

I'm making an intro video for this game I play and I have music playing in the video that I want people to be able to mute/unmute when pressing spacebar; No idea if I'm going it right I essentially reached this point from pulling various other bits of code together from elsewhere. It doesn't work at all, please help.

Please note: this is not the entire HTML File, I can provide it if necessary. It just has progress bars and stuff in.

this is my code so far:

 <video class="introVideo" id="introVideo" width="1920" height="1080" autoplay muted> <source src="video.mp4" type="video/mp4"> </video> <script> var myVideo = document.getElementById("introVideo"); function onKeyDown(event) { switch (event.keyCode) { case 32: //SpaceBar if (muted) { myVideo.muted = true(); muted = false; } else { myVideo.muted = false(); muted = true; } break; } return false; } </script> 

You just miss one part, link your keyDown function to user action. You ca ndo it like this:

myVideo.addEventListener('keydown', onKeyDown);

You can add this code just before "< /script>" tag close. Here is documentation for addEventListener => https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Edit: You will probably need also focus your video tag by default, otherwise it will not work. But if you want whole you page interact to mute/unmute do

document.body.addEventListener('keydown', onKeyDown);
  • It seems that the variable muted is not initialised.
  • There is no such thing as true() and false()
  • Your function does not bound to some event. So you should either bind it to some element (with addEventListener ) or to bind with the old approach of using ELEMENT.onXXX
  • In order for document.getElementById to always work, you better wait for the document ready event (better to use with jQuery) or the bit later, window.onload event.

So the modifications above, plus a bit simpler logic can be written as:

<video class="introVideo" id="introVideo" width="1920" height="1080" autoplay muted>
  <source src="video.mp4" type="video/mp4">
</video>
<script>
window.onload = function(){
  var myVideo = document.getElementById("introVideo");

  document.onkeydown = function(event) {
    switch (event.keyCode) {
      case 32: //SpaceBar
        myVideo.muted = !myVideo.muted;
      break;
    }
    return false;
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM