Dan Cristian
Dan Cristian

Reputation: 13

reactjs change currentTime of audio while playing

I have this audio player and I need to be able to change the currentTime while the audio file is playing. Currently I can change the currentTime only when audio is paused. What should I change in my code?

playAudio(playing_url) {
    let audio = new Audio(playing_url);
    audio.addEventListener('loadedmetadata', () => {
        audio.currentTime = audio.duration * this.state.progress;
        console.log('event listener', audio.duration);
    });
    if(!this.state.playing) {
        audio.play();
        this.setState({
            playing: true,
            playing_story: playing_url,
            audio
        });
    } else {
        if(this.state.playing_story === playing_url) {
            this.state.audio.pause();
            this.setState({
                playing: false
            })
        } else {
            this.state.audio.pause();
            audio.play();
            this.setState({
                playing: true,
                playing_story: playing_url,
                audio
            })
        }
    }

}

Upvotes: 0

Views: 3056

Answers (1)

Amir Mohammad Moradi
Amir Mohammad Moradi

Reputation: 887

you should update currentTime by state like this :

audio.addEventListener('loadedmetadata', () => {
    // some code to calculate currentTime for first time
    audio.currentTime = this.state.currentTime;
});

function changeCurrentTime(time) { 
  this.setState({ currentTime: time })
}

Upvotes: 1

Related Questions