将HTML音频置于REACT.js状态

时间:2017-01-03 01:49:35

标签: javascript reactjs audio html5-audio

我正在构建一个音频组件的问题。我想检查音频是否正在播放并将其作为布尔值isPlaying置于状态。我也希望currentTime处于州内。这是我到目前为止组件的内容。当我尝试绑定音频时,声明它不能正常工作。因此,如果我进入开发工具并尝试更改状态,它对音频没有影响。

class AudioPlayer extends  React.Component{
  constructor(){
    super();
    this._playingAudio = this._playingAudio.bind(this); 
    this._playPauseUsingState = this._playPauseUsingState.bind(this); 
    this._setAudio = this._setAudio.bind(this); 
    this._syncAudio = this._syncAudio.bind(this);
    this.state = {
      currentTime:0,
      isPlaying:false
    }
  }
  _syncAudio(time) {
    this.setState({
      currentTime:time,
    })
  }

  _setAudio(callback){
    this.setState({
      isPlaying:callback
    })
  }

  _playPauseUsingState(){
    if(this.state.isPlaying) {
      this.audioPlayer.play()
    } else {
      this.audioPlayer.pause()
    }
  }

  _playingAudio(){
    var self = this;
    this.audioPlayer.addEventListener('timeupdate', function(){
      self._syncAudio(this.currentTime)
    })

    this.audioPlayer.addEventListener('playing', function(){
      self._setAudio(true)
    })

    this.audioPlayer.addEventListener('pause', function(){
      self._setAudio(false)
    })
  }

  componentDidMount(){
    this._playingAudio();
    this._playPauseUsingState();
  }

  componentDidUpdate(){
    this._playPauseUsingState();
  }

  render(){
    return (
      <div className='audio'>
        <pre>{JSON.stringify(this.state, null, 2)}</pre>
        <audio ref={(audio) => {this.audioPlayer = audio}} className="audio-player" src="audio_src.mp3" preload controls></audio>
      </div>
    )
  }
}
 ReactDOM.render((
  <AudioPlayer />
),appTarget);

0 个答案:

没有答案