Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to play a music with <audio> in react?

I am creating a simple react app that requires playing music with a given url. I tried to test with a hard coded music url and use the <audio> tag to play the music just as we do in HTML.

class Music extends React.Component {
  render() {

    return (
      <span>

        <audio src="URL">
  </span>

    )
  }
}

But this will not compile. What is the simplest way to play a music in a react app?

like image 942
Dawn17 Avatar asked Dec 03 '17 08:12

Dawn17


People also ask

How do you play sound on click react?

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL. Then we call play on the created object to play the audio clip. We create the audio object with the Audio constructor with the MP3 file URL as its argument. Then we call audio.

How do I import mp3 into react?

Hi ksk to play an mp3 file or render an image in react you have to first import it as an alias and then at the path place you can use that alias. Take this example for clear understanding. in the above the mp3 file is in a directory outside the code directory and then inside the assets folder.


1 Answers

One solution is with HTML5 Audio. Create new Audio object and control it with custom Play / Pause buttons.

Basic example:

class Music extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      play: false,
      pause: true,
    }
    this.url = "http://streaming.tdiradio.com:8000/house.mp3";
    this.audio = new Audio(this.url);
  }

  play = () => {
  this.setState({ play: true, pause: false })
    this.audio.play();
  }
  
  pause = () => {
  this.setState({ play: false, pause: true })
    this.audio.pause();
  }
  
  render() {
    
  return (
    <div>
      <button onClick={this.play}>Play</button>
      <button onClick={this.pause}>Pause</button>
    </div>
    );
  }
}

ReactDOM.render(
  <Music />,
  document.getElementById('container')
);
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Also you can use addEventListener to control and handle Play / Pause.

Play:

this.audio.addEventListener('play', () => {
  this.setState({
    play: true,
    pause: false,
  })
});

Pause:

this.audio.addEventListener('pause', () => {
  this.setState({
    play: false,
    pause: true,
  })
});

Documentation and examples:

Audio/Video Event Listener

MDN HTML5 Audio

Important note:

The HTML5 Audio element does not have a stop() function, so the audio after pause() is still loading (buffering in background).

This is a solution: HTML5 Video: Force abort of buffering

JSFIddle: https://jsfiddle.net/y2j0vzbe/

Hope this can help.

like image 154
Marko Savic Avatar answered Oct 04 '22 20:10

Marko Savic