P
P
Paxest2019-04-09 20:45:51
React
Paxest, 2019-04-09 20:45:51

How to play audio on button click in React?

Good day!
I 'm doing tasks on freecodecamp.com -- https://learn.freecodecamp.org/front-end-libraries...
I'm trying to implement playback, I looked at the code from the link above, but I wanted to use my own method.
I'm trying to set using setState({url: 'new url'}), but the code doesn't work, but if you initially place a link to the melody in this.state ={url: "https//..."}, then the button plays on click melody.
I tried to solve it in several ways, when I used onClick={document.getElementById('Eee').play()} on the second button, then when writing .play(), everything disappears from the screen, the react refuses to work if you remove .play() and write on the second button onClick={document.getElementById('Eee')} buttons appear but audio doesn't work.
Can you please tell me where the error has crept in and how to reproduce the url change and audio playback by accessing this.state.url?

const musicButton = [
  {
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
    letter: "Q",
    numButton: 81,
    soundsName: "Heat-Heat"
  },
  {
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
    letter: "W",
    numButton: 87,
    soundsName: "Heat-2-Heat"
  }];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      music: [...musicButton],
      url: ""
    };

  this.play = this.play.bind(this);
  this.audio = new Audio(this.state.url);
};

play = () => {
    let buttonMusic = this.state.music[0].url;
    this.setState({url: buttonMusic});
    this.audio.play();
};

  render() {
      return (
      <div>
        <section id="display">
          <h1>Проверка ссылки</h1>
          <h2>{ this.state.music[1].url}</h2>
          <button onClick={this.play} value='W'>W</button>
          <audio id='Eee'><source src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3" /></audio>
          <button onClick={document.getElementById('Eee').play()}'>E</button>
        </section>
      </div>
    );
  }
}

React.render(<App />, document.getElementById("app"));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-04-09
@Paxest

class App extends React.Component {
  state = {
    music: musicButton,
  }

  onClick = e => {
    if (this.audio) {
      this.audio.pause();
    }
    this.audio = new Audio(e.target.dataset.url);
    this.audio.play();
  }

  render() {
    return (
      <div>
        {this.state.music.map(n => (
          <button onClick={this.onClick} data-url={n.url} key={n.numButton}>{n.soundsName}</button>
        ))}
      </div>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question