I am working on a Drum machine project where I am failing to pass a task. the task is:
When I press the trigger key associated with each .drum-pad, the audio clip contained in its child element should be triggered (e.g. pressing the Q key should trigger the drum pad which contains the string "Q", pressing the W key should trigger the drum pad which contains the string "W", etc.).
My code so far:
class Drumset extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMount() {
document.addEventListener("keydown", this.handleKeyPress);
}
handleClick = (event) => {
const audio = event.target.children[0];
audio.play();
};
handleKeyPress = (event) => {
if (
event.key === "q" ||
event.key === "w" ||
event.key === "e" ||
event.key === "a" ||
event.key === "s" ||
event.key === "d" ||
event.key === "z" ||
event.key === "x" ||
event.key === "c"
) {
const audio = event.target.children[0];
audio.play;
console.log("key pressed");
}
};
render() {
return (
<div>
<div id="drum-machine" class="containerx box-middle">
<div id="display" onKeyDown={this.handleKeyPress}>
<div class="container">
<div class="row">
<div class="col">
<button
type="button"
class="drum-pad"
id="Heater-1"
onClick={this.handleClick}
>
Q
<audio
class="clip"
id="Q"
src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
type="audio/mpeg"
></audio>
</button>
My problem is that, whenever I press a key, the handleKeyPress() function works but the audio doesn't play (the console shows the print). How to play the audio when I press the associated button?
audio.play;does nothing, just references the function. Did you meanaudio.play()? - ggorlen