【问题标题】:Playing sound by keypress using Javascript and HTML使用 Javascript 和 HTML 通过按键播放声音
【发布时间】:2022-10-23 05:00:11
【问题描述】:

我是网络开发的超级新手,我正在尝试让这个简单的在线鼓组工作示例。该网站加载正常,但是当我按下一个键时没有任何反应。我知道这是一个非常愚蠢的问题,但我有点难过。谢谢!

<!DOCTYPE html>
<html>
<body>

<h2>Simple Drumkit!</h2>
<p>C = Kick, A = Crash, Z and X = Snare!</p>

<script>
const sounds = {
  'KeyZ': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyX': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyA': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/crash1.ogg',
  'KeyC': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/kik.ogg'
}

const play = sound => {
  console.log("playing",sound)
  var audio = new Audio(sound);
  audio.play();
}

window.addEventListener('keypress', function(e) { console.log(e.code)
  if (sounds[e.code]) {
    console.log("clicking",e.code)
    document.getElementById(e.code).click()
  }  
})
</script> 

</body>
</html>

【问题讨论】:

    标签: javascript html audio


    【解决方案1】:

    对我来说,我会使用功能并完美地传递价值观及其作品。

    当用户按下键然后该特定函数播放声音时,我正在调用该函数。它几乎没有潜伏由于外部链接可能正在播放。

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>Simple Drumkit!</h2>
    <p>C = Kick, A = Crash, Z and X = Snare!</p>
    
    <script>
        
    const sounds = {
      'KeyZ': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
      'KeyX': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
      'KeyA': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/crash1.ogg',
      'KeyC': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/kik.ogg'
    }
    
    //Changed into function
    function playSound(sound) {
      console.log("playing",sound)
      var audio = new Audio(sound);
      audio.play();
    }
    
    window.addEventListener('keypress', function(e) { console.log(e.code)
      if (sounds[e.code]) {
        console.log("clicking",e.code);
    
        // calling function and passing sounds[e.code] which is address as arguments
        playSound(sounds[e.code]);
      }  
    })
    </script> 
    
    </body>
    </html>
    

    【讨论】:

    • 啊,这实际上更有意义,非常感谢!
    猜你喜欢
    • 2022-08-05
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多