Using Sound Bank Switch Button

Hello,

I’m trying to make a drum machine using react hooks. I’m trying to implement a sound bank button which changes between two sound banks.

I can get it to work using handleclick, but problems arise when I try and do it using an event listener (pressing q,w,e for example to trigger the drum noises). For some reason the first time around it works but as soon as I click change bank, it’s playing from both banks at the same time.

Any help greatly appreciated.

Here’s my code so far:

import React, { useState} from 'react';

const audioSamples = {
  bank1:{
  q: new Audio("http://dight310.byu.edu/media/audio/FreeLoops.com/3/3/Free%20Kick%20Sample%208-900-Free-Loops.com.mp3"),
  w: new Audio("http://www.denhaku.com/r_box/sr16/sr16sd/alloysnr.wav"),
  e: new Audio("http://dight310.byu.edu/media/audio/FreeLoops.com/5/5/Long%20Open%20Hi%20Hat%20002-1653-Free-Loops.com.mp3"),
  a: new Audio("http://dight310.byu.edu/media/audio/FreeLoops.com/4/4/Korg%20Ride%20Cymbal%202-2526-Free-Loops.com.mp3"),
  s: new Audio("http://electrongate.com/dmxfiles/DXCRASH.wav"),
  d: new Audio("http://cd.textfiles.com/10000soundssongs/WAV/COWBELL1.WAV")
  },
  bank2:{
    q: new Audio("http://cd.textfiles.com/10000soundssongs/WAV/EERIE_1.WAV"),
    w: new Audio("http://www.denhaku.com/r_box/linn/congal.wav"),
    e: new Audio("http://electrongate.com/dmxfiles/conga.wav"),
    a: new Audio("http://dight310.byu.edu/media/audio/FreeLoops.com/4/4/Korg%20Ride%20Cymbal%202-2526-Free-Loops.com.mp3"),
    s: new Audio("http://electrongate.com/dmxfiles/DXCRASH.wav"),
    d: new Audio("http://cd.textfiles.com/10000soundssongs/WAV/COWBELL1.WAV")
    }
}
   
function App() {

  const [banknum, setBanknum] = useState(1); 

  function changeBank() {
    console.log(banknum)
    setBanknum(prevBanknum => prevBanknum === 1 ? prevBanknum = 2 : prevBanknum = 1)
  }

  function handleClick(e) {
    if(banknum == 1){
    audioSamples.bank1[e.target.id].play()
    }
    else {audioSamples.bank2[e.target.id].play() }
    }

    document.addEventListener('keydown', function(e) {
      if(audioSamples.bank1[e.key] && banknum === 1){
        audioSamples.bank1[e.key].load()
        audioSamples.bank1[e.key].play()
        }
    else if (audioSamples.bank2[e.key] && banknum === 2) { 
      audioSamples.bank2[e.key].load()
      audioSamples.bank2[e.key].play()
    }
      }); 

  return (
    <div id="DrumMachine" className="App" >
      <button id="q" onClick={handleClick} >Q</button>
      <button id="w" onClick={handleClick}>W</button>
      <button id="e" onClick={handleClick}>E</button>
      <button id="a" onClick={handleClick}>A</button>
      <button id="s" onClick={handleClick}>S</button>
      <button id="d" onClick={handleClick}>D</button>
      <button id ="banks" onClick={changeBank}>Change Bank
      </button>
    </div>
  );
}
export default App;