0

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>
imjared
  • 19,492
  • 4
  • 49
  • 72
65535
  • 523
  • 1
  • 10
  • 32
  • 1
    https://stackoverflow.com/questions/9419263/how-to-play-audio – imjared Sep 16 '20 at 23:39
  • 1
    Does this answer your question? [How to play audio?](https://stackoverflow.com/questions/9419263/how-to-play-audio) – Grismar Sep 16 '20 at 23:51
  • Yes, it helped a lot. However, the correct way is to retrieve the entire ` – 65535 Sep 16 '20 at 23:57

0 Answers0