不循环播放声音文件

Playing sound file without looping

纯JavaScript。想要在按下键时播放(打字机)声音(.wav)。同时,只要按下该键,灯就会亮起并一直亮着。 问题是声音文件一直循环播放,直到我松开按键。有没有办法让声音文件只播放一次而不循环播放,即使我按住键不放?

script.js

window.addEventListener("keydown", lightOn, false);
window.addEventListener("keyup", lightOff, false);
let click = new Audio("../sound/click.wav");

function lightOn(key) {
  switch (key.keyCode) {
    case 65:
      // click.loop = false; <- tried this but does not prevent looping
      click.play();
      document.getElementById("a").style.color = "goldenrod";
  }
}

function lightOff() {
  document.querySelector(".typing").style.color = "#ccc";
}

运行 剪下保留密钥并查看控制台.....

window.addEventListener("keydown", e => {
  console.log(e.key)
});

现在可以防止重复

    window.addEventListener("keydown", e => {
      if(e.repeat) 
        return
      console.log(e.key)
    });

Document is here. It says that it must be good to call click.pause(). But it must not be result you expect. To control in detail requires Web Audio API。比前者难多了,但一定很刺激,试试吧!