react-audio-player icon indicating copy to clipboard operation
react-audio-player copied to clipboard

Make playback state controlled

Open Secretmapper opened this issue 6 years ago • 3 comments

Right now, if we want to control the play state of an element, we would have to use the actual DOM element using ref:

this.audioEl.play()

Seeing as this library is a wrapper it would be great if the various controls are exposed through more idiomatic react code, i.e.:

<ReactAudioPlayer state={ReactAudioPlayer.STATE.PLAYING} /> // or paused/stopped

Secretmapper avatar Jan 03 '19 00:01 Secretmapper

This is like the number 1 thing I would expect from a react component for an audio player

josh-peterson-bose avatar Mar 30 '20 17:03 josh-peterson-bose

import { useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import ReactAudioPlayer from 'react-audio-player'

export default function AudioPlayer({
  playback: { playing, muted },
  src,
}) {
  const playerRef = useRef()

  useEffect(() => {
    if (playing) {
      playerRef.current.audioEl.current.play()
    } else {
      playerRef.current.audioEl.current.pause()
    }
  }, [playing])

  return (
    <ReactAudioPlayer
      ref={playerRef}
      autoPlay={playing}
      muted={muted}
      src={src}
    />
  )
}
AudioPlayer.propTypes = {
  playback: PropTypes.object.isRequired,
  src: PropTypes.string.isRequired,
}

hermanskurichin avatar Jan 17 '21 19:01 hermanskurichin

This approach results in a race condition when manipulating playback state with this approach and by directly interacting with the player simultaneously. play() and pause() are asynchronous, and it seems that higher "priority" is given to changes to player state from interacting with the player itself than to the changes to player state caused by this approach. I do not think this is a viable path forward for anyone hoping to "fully React-ify" the audio component.

jumble avatar Feb 17 '23 17:02 jumble