[英]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. 请注意:这不是整个HTML文件,如有必要,我可以提供。 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. 您只需错过一个部分,将keyDown功能链接到用户操作。 You ca ndo it like this: 你喜欢这样:
myVideo.addEventListener('keydown', onKeyDown);
You can add this code just before "< /script>" tag close. 您可以在“</ script>”标记关闭之前添加此代码。 Here is documentation for addEventListener => https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener 以下是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);
muted
is not initialised. 似乎muted
变量未初始化。 true()
and false()
没有true()
和false()
这样的东西 addEventListener
) or to bind with the old approach of using ELEMENT.onXXX
所以你应该将它绑定到某个元素(使用addEventListener
)或者使用旧的方法绑定ELEMENT.onXXX
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. 为了使document.getElementById
始终有效,您最好等待document
ready
事件(最好与jQuery一起使用)或稍后的window.onload
事件。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.