Home » Javascript » Audio Player in ReactJS

Audio Player in ReactJS

Posted by: admin June 30, 2018 Leave a comment

Questions:

The title isn’t self-descriptive. I faced some problems creating some flexible audio player. The main problem is that I can’t force change the state of the audio element after it is initiated. For example, I can’t trigger play/stop for it because I don’t know how to trigger its functions from outside. The element needs to be accessible from anywhere in the code, well, mostly down the structure and some global events will cause it to change song, volume, trigger play.

class Player extends React.Component {
  constructor(props) {
    super(props);
    //I thought I would be able to control everything with props and states
    this.state = {playstate: this.props.playstate};
    this.handlePlay.bind(this);
  }

  componentDidMount() {
    this.handlePlay();
  }

  togglePlay() { //I don't understand how to reach this, or reproduce its behavior
    this.setState({ playstate: !this.state.playstate }, this.handlePlay);
  }

  handlePlay() {
    if (this.state.playstate) this.refs.audio.play();
    else this.refs.audio.pause();
  }

  render() {
    return (
      <audio className="audio-element" {...this.props} ref="audio"></audio>
    );
  }
};

So another example. I have react router set up. After switching to another page the song needs to be changed. React router renders another component to view new data and, I guess, this way I will create new player instead of updating previous. Is it possible to update audio player switching the song?

It sounds so easy to me as just calling a function, but React structure is a little different which confuses.

Answers: