I have been stuck on this test for days . 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
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!
Iâd like to see this through too, so keep me updated if you want Itâs good to work on these things with someone, and I havenât done much of that yet.