单击键/按钮时如何播放每种声音?

时间:2018-07-23 01:38:45

标签: javascript

我搞不清这个练习,根据您按的键(N,S,B或F)播放声音。

当单击按钮时,我还想播放每种声音,因此它也适用于移动设备,用户可以选择播放声音。解决此问题的最佳方法是什么?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Key sounds</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>


  <div class="keys">
    <div data-key="78" class="key">
      <kbd>N</kbd>
      <span class="sound">nani</span>
    </div>
    <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">scrambling</span>
    </div>
    <div data-key="66" class="key">
      <kbd>B</kbd>
      <span class="sound">barber</span>
    </div>
    <div data-key="70" class="key">
      <kbd>F</kbd>
      <span class="sound">face</span>
    </div>
  </div>

  <audio data-key="78" src="sounds/nani.m4a"></audio>
  <audio data-key="83" src="sounds/scrambling.m4a"></audio>
  <audio data-key="66" src="sounds/barber.m4a"></audio>
  <audio data-key="70" src="sounds/chap.m4a"></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; // stop the function from running all together
      audio.currentTime = 0; // rewind to the start
      audio.play();
      key.classList.add('playing');
    }

    function removeTransition(e) {
      if(e.propertyName !== 'transform') return; // skip it if it's not a transform
      this.classList.remove('playing');
    }

    const keys = document.querySelectorAll('.key');
    keys.forEach(key => key.addEventListener('transitionend', removeTransition));
    window.addEventListener('keydown', playSound);
  </script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码扩展代码:

keys.forEach(element => {

   // Add a click event listener to each ".key" element, so that
   // clicking plays the corresponding audio
   element.addEventListener('click', () => {

       // Fetch the key for the audio object that matches the key of 
       // this element
       const audioKey = element.getAttribute('data-key');

       // Query the document for the audio object corresponding to 
       // this element's key. 

       // The document.querySelector will get the first element from 
       // the document that matches the selector you pass. 

       // The audio[data-key="${ audioKey } part means "get an audio 
       // element that has a data-key attrbitute whose value matches 
       // that of the current element's "data-key" (ie 78, 83, etc)

       const audio = document.querySelector(`audio[data-key="${ audioKey }"]`);

       // Play the audio in the same way as you currently are
       audio.currentTime = 0;
       audio.play();
       element.classList.add('playing');
   })
})