Drum machine - test 6

I have been stuck on this test for days :tired_face:. I cant seem to find a solution that works. The audio() API works, but creates new audios. refs kinda work but makes all the key presses play the same sound. can anyone help?
https://codepen.io/Logan_code/pen/poNwBMX

Challenge: Build a Drum Machine

Link to the challenge:

Hey there,

So your console log is returning an error each time, have you looked much into this yet?
It’s logging the audio file for the C key, and then giving you a cannot get keyCode of undefined error.

What you have you looked at so far as to why it’s doing this?
React useRef docs could help out here.

i know that the error is because of the way im accessing the array, its the only way of getting the keyCodes without making a new array for just keycodes.

the problem i want to solve is that any key pressed plays <audio class='clip' src='https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3' id='C'></audio>

Sure, it’s a tricky one! I’m using this debugging as practice for myself, so my solution may not be the most efficient.

The ref doesn’ serve any purpose here I don’t think.
It could be simpler to use the playSound method to see if a key was pressed, or if the button was clicked. It will also help you keep your code DRY.

By having one playSound method, you could assign the audio element like so:


// note that we removed the ref binding, and the keypress binding and function
// also removed the id and ref from the audio file. 

playSound=(e)=>{
    this.setState({
      play:!this.state.play,
    });
    
// this is checking if `e.key` exists. If it does (truthy) then it assigns 
// the element variable otherwise it's undefined
    const element = e.key && document.getElementById(e.key.toUpperCase())

// the below checks if element has been assigned in the line above. 
// If it has, then the querySelector is assigned from the element variable, if not, then it means it's been clciked, and get's it from the `e.target`
    const audio = element ? element.querySelector('audio') : e.target.querySelector('audio')

    audio.play();
    audio.currentTime = 0;
  }

You should also not have any DOM elements with the same id, this is often a cause of bugs, and is considered bad practice.

This get’s it working, but may not be clear why or how, so please ask more questions! :slight_smile:


but it doesn’t pass the tests :face_with_hand_over_mouth: :confounded:

I think this may help you move forward a little, and hopefully gives you some “food for thought” :smiley:

thanks alot mark, progress is progress :grin:

1 Like

I’d like to see this through too, so keep me updated if you want :slight_smile: It’s good to work on these things with someone, and I haven’t done much of that yet.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.