使用JavaScript多次播放声音文件(在第一次播放完之前)?

时间:2017-05-18 02:46:37

标签: javascript ecmascript-6

我正在编写一本教程来改进我的JavaScript。我需要制作一个鼓组件'按键发出声音的地方。

我在这里有一个代码笔,虽然它不能完全工作,因为我无法引用音频文件:https://codepen.io/anon/pen/vmzjPy

如果你慢慢点击键,我已经开始工作了。但是,如果您快速点击相同的键,声音将不会播放多次,直到第一个实例播放完毕。

 <div class="keys">
    <div data-key="65" class="key">
      <kbd>A</kbd>
      <span class="sound">clap</span>
    </div>
    <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">hihat</span>
    </div>
    <div data-key="68" class="key">
      <kbd>D</kbd>
      <span class="sound">kick</span>
    </div>
    <div data-key="70" class="key">
      <kbd>F</kbd>
      <span class="sound">openhat</span>
    </div>
    <div data-key="71" class="key">
      <kbd>G</kbd>
      <span class="sound">boom</span>
    </div>
    <div data-key="72" class="key">
      <kbd>H</kbd>
      <span class="sound">ride</span>
    </div>
    <div data-key="74" class="key">
      <kbd>J</kbd>
      <span class="sound">snare</span>
    </div>
    <div data-key="75" class="key">
      <kbd>K</kbd>
      <span class="sound">tom</span>
    </div>
    <div data-key="76" class="key">
      <kbd>L</kbd>
      <span class="sound">tink</span>
    </div>
  </div>

  <audio data-key="65" src="sounds/clap.wav"></audio>
  <audio data-key="83" src="sounds/hihat.wav"></audio>
  <audio data-key="68" src="sounds/kick.wav"></audio>
  <audio data-key="70" src="sounds/openhat.wav"></audio>
  <audio data-key="71" src="sounds/boom.wav"></audio>
  <audio data-key="72" src="sounds/ride.wav"></audio>
  <audio data-key="74" src="sounds/snare.wav"></audio>
  <audio data-key="75" src="sounds/tom.wav"></audio>
  <audio data-key="76" src="sounds/tink.wav"></audio>

<script>

  'use strict';

  const keyElems = document.getElementsByClassName('key');
  const soundElems = document.getElementsByTagName('audio');

  const highlight = function(elem) {
    elem.classList.add('playing');
    setTimeout(function(){
        elem.classList.remove('playing');
    }, 300);
  }

  const makeSound = function(val){
    for (const soundsElem of soundElems) {
      const soundsElemVal = soundsElem.getAttribute('data-key');
      if (val === soundsElemVal) {
        soundsElem.play();
      }
    }
  }

  const keyPressedSoundVal = function(obj) {
    //console.log('keyPressedSoundVal');
    const keyPressed = obj.key;
    for (const keyElem of keyElems) {
      const val = keyElem.getElementsByTagName('kbd')[0].textContent.toLowerCase();
      if (keyPressed === val) {
        highlight(keyElem);
        const val = keyElem.getAttribute('data-key');
        makeSound(val);
      }
    }
  }

  document.addEventListener("keypress", keyPressedSoundVal);

</script>

1 个答案:

答案 0 :(得分:0)

音频元素在完成播放之前不会再播放,因此解决方法是在播放前回放音频元素:

IPConfig|FindStr/IRC:"IPv4 .*: 10.0.50.">Nul 2>&1 && (Call script.bat) || (
    IPConfig|FindStr/IRC:"IPv4 .*: 10.0.60.">Nul 2>&1 && Call script2.bat)