lhz516 / react-h5-audio-player

React audio player component with UI. It provides time indicator on both desktop and mobile devices.
https://codepen.io/lhz516/pen/dyGpmgP
MIT License
587 stars 91 forks source link

Play / pause inifinite loop #206

Closed Simoneth closed 1 year ago

Simoneth commented 1 year ago

Hi, Congratulations for this plugin which is very useful. I have only one problem, I don't understand what I'm doing wrong but when I press play and pause several times, the player stops responding and continues by itself to change from play to pause every tenth of a second. I have react 18 node 13 and latest version of your plugin, I tried this on chrome 112.0.5615.137 from my Mac.

This is basically how I developed the thing: I have 2 components, the player and the button, where the playerState is my context.

// Player
useEffect(() => {
    if (playerRef.current) {
        if (playerState) {
            playerRef.current.audio.current.play();
        } else {
            playerRef.current.audio.current.pause();
        }
    }
}, [playerState])

<AudioPlayer
    autoPlay
    autoPlayAfterSrcChange={false}
    preload='metadata'
    src={musicTracks[trackIndex]?.src}
    onPlay={() => setPlayerState(true)}
    onPause={() => setPlayerState(false)}
    ref={playerRef}
    playerState={playerState}
/>

// Button
const clickEvent = (e, type) => {
    e.preventDefault();

    ...

    if (type === 0) setPlayerState(true);
    else if (type === 1) setPlayerState(false);

}

<Button onClick={(e) => clickEvent(e, 0)}>Play</Button>
<Button onClick={(e) => clickEvent(e, 1)}>Pause</Button>

When the playerState changes, the player play and pause audio. What am I doing wrong?