There is a <button>
element that has a child <audio>
element. The id
of the button is passed into a playSound()
function that selects the src
of the <audio>
element. However, when trying to play the sound using sound.play();
an error is given: sound.play is not a function
.
How can the sound be played when the button is clicked? Any help would be greatly appreciated.
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
//import './style.css';
class DrumMachine extends React.Component {
constructor(props) {
super(props);
this.state = {
}
this.playSound = this.playSound.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress);
}
handleKeyPress(e) {
if (e.keyCode === this.props.keyCode) {
this.playSound();
}
}
playSound(id) {
let sound = document.getElementById(id).childNodes[0].src;
console.log(sound)
sound.play();
}
render() {
return (
<div id="drum-machine">
<h1 id="title">Drum Machine</h1>
<div id="display"></div>
<div>
<button id="81" className="drum-pad" onClick={e => this.playSound(e.target.id)}><audio className="clip" id="Q" src='https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'></audio> Q </button>
</div>
</div>
);
}
}
ReactDOM.render(<DrumMachine />, document.getElementById("app"));
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Drum Machine</title>
</head>
<body>
<main>
<div id="app"></app>
</main>
</body>
</html>