Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Forked from gaearon/AudioPlayer.jsx
Last active October 25, 2016 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsharp/9a4a82062b9994c88db1f0fd1f5e7cf4 to your computer and use it in GitHub Desktop.
Save davidsharp/9a4a82062b9994c88db1f0fd1f5e7cf4 to your computer and use it in GitHub Desktop.
React <audio> wrapper (for ^15.3.2)
'use strict';
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
class AudioPlayer extends Component {
componentDidMount() {
var node = ReactDOM.findDOMNode(this);
node.addEventListener('progress', this.handleProgress.bind(this));
node.addEventListener('timeupdate', this.handleTimeUpdate.bind(this));
node.addEventListener('ended', this.handleMediaEnd.bind(this));
this.updateIsPlaying();
}
componentDidUpdate(prevProps) {
if (prevProps.source !== this.props.source) {
this.updateSource();
}
if (prevProps.isPlaying !== this.props.isPlaying) {
this.updateIsPlaying();
}
if (prevProps.defaultTime !== this.props.defaultTime) {
this.updateCurrentTime();
}
}
componentWillUnmount() {
var node = ReactDOM.findDOMNode(this);
node.removeEventListener('progress', this.handleProgress.bind(this));
node.removeEventListener('timeupdate', this.handleTimeUpdate.bind(this));
node.removeEventListener('ended', this.handleMediaEnd.bind(this));
}
render() {
return (
<audio preload='none'>
<source src={this.props.source}
type='audio/mpeg' />
</audio>
);
}
handleTimeUpdate() {
var node = ReactDOM.findDOMNode(this),
currentTime = node.currentTime,
trackDuration = node.duration;
this.props.onTimeUpdate({
currentTime: currentTime,
trackDuration: trackDuration
});
}
handleMediaEnd() {
ReactDOM.findDOMNode(this).currentTime = 0;
this.props.onEnd();
}
handleProgress() {
var node = ReactDOM.findDOMNode(this),
trackDuration = node.duration,
buffered = node.buffered;
this.props.onProgress({
trackDuration: trackDuration,
buffered: buffered
});
}
updateCurrentTime() {
var node = ReactDOM.findDOMNode(this);
if (node.readyState) {
node.currentTime = this.props.defaultTime;
}
}
updateIsPlaying() {
var node = ReactDOM.findDOMNode(this),
isPlaying = this.props.isPlaying;
if (isPlaying) {
node.play();
} else {
node.pause();
}
}
updateSource() {
var node = ReactDOM.findDOMNode(this),
isPlaying = this.props.isPlaying;
node.pause();
this.props.onTimeUpdate({
currentTime: 0,
trackDuration: node.duration
});
node.load();
if (isPlaying) {
node.play();
}
}
}
AudioPlayer.propTypes= {
source: PropTypes.string.isRequired,
isPlaying: PropTypes.bool.isRequired,
defaultTime: PropTypes.number,
onProgress: React.PropTypes.func.isRequired,
onTimeUpdate: React.PropTypes.func.isRequired,
onEnd: React.PropTypes.func.isRequired
}
export default AudioPlayer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment