使javascript按键声音彼此独占?

时间:2018-02-25 16:15:20

标签: javascript keypress keydown

我有一个简单的网站,可以触发javascript按键事件的声音。我需要它才能工作,以便在触发另一个声音时前一个声音停止。例如,当我按下下一个和弦时,前一个和弦停止播放。我还需要创建排他性组,以便下一个和弦停止前一个和弦,但不会停止鼓。

  <div class="keys">
    <div data-key="90" class="key"> 
      <kbd>Z</kbd>
      <span class="sound">Intro Drums</span>
    </div>
    <div data-key="88" class="key">
      <kbd>X</kbd>
      <span class="sound">Verse Drums</span>
    </div>
    <div data-key="67" class="key">
      <kbd>C</kbd>
      <span class="sound">Build Drums</span>
    </div>
    <div data-key="86" class="key">
      <kbd>V</kbd>
      <span class="sound">Drop Drums</span>
    </div>
    <div data-key="66" class="key">
      <kbd>B</kbd>
      <span class="sound">Bmajor(VI)</span>
    </div>
    <div data-key="78" class="key">
      <kbd>N</kbd>
      <span class="sound">C#major(VII)</span>
    </div>
    <div data-key="77" class="key">
      <kbd>M</kbd>
      <span class="sound">D#m(i)</span>
    </div>
    <div data-key="188" class="key">
      <kbd><</kbd>
      <span class="sound">Bbm(v)</span>
    </div>
  </div>   

  <audio data-key="90" src="sounds/drums/Drums1_Tambo.mp3"></audio>
  <audio data-key="88" src="sounds/drums/Drums2_Verse.mp3"></audio>
  <audio data-key="67" src="sounds/drums/Drums3_BuildUp.mp3"></audio>
  <audio data-key="86" src="sounds/drums/Drums4_Drop.mp3"></audio>
  <audio data-key="66" src="sounds/dropChords/ChordsBass1_Bmaj(VI).mp3"></audio>
  <audio data-key="78" src="sounds/dropChords/ChordsBass2_CSharpmaj(VII).mp3"></audio> 
  <audio data-key="77" src="sounds/dropChords/ChordsBass3_DSharpm(i).mp3"></audio>
  <audio data-key="188" src="sounds/dropChords/ChordsBass4_Bbm(iv).mp3"></audio>

<script>

  function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
    if(!audio) return; // stops the function from running
    audio.currentTime = 0; //rewind to the start
    audio.play();
    key.classList.add('playing');
  };

  function removeTransition(e) {
    if(e.propertyName !== 'transform') return;
    this.classList.remove('playing');
  }

  const keys = document.querySelectorAll('.key');
  keys.forEach(key => key.addEventListener('transitionend', removeTransition));

  window.addEventListener('keydown', playSound);
</script>


</body>
</html>

0 个答案:

没有答案