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.