簡體   English   中英

單擊鍵/按鈕時如何播放每種聲音?

[英]How can I play each sound when a key/button is clicked?

我對這個練習感到困惑,根據您按的鍵(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>

您可以使用以下代碼擴展代碼:

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');
   })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM