How to integrate wavesurfer with existing audio - React

328 Views Asked by At

I have an audio element that is being used in multiple other components to play songs. I would like to integrate wavesurfer to this already existing audio. This issue https://github.com/katspaugh/wavesurfer.js/issues/986 says I can load the audio tag, but I get errors when doing it. I believe it's because my audio component is actually of type ForwardRefExoticComponent<Props & RefAttributes<HTMLAudioElement>> instead of just an HTMLAudioElement

const WavesurferComponent = (props: Props) => {
  const { isPlaying } = props;

  const [waver, setWaver] = useState<MODWaveSurfer | null>(null);

  const waveformRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!waveformRef.current) return;

    const modedWaveSurfer = WaveSurfer as unknown as MODWaveSurfer;

    const wavesurfer = modedWaveSurfer.create({
      barWidth: 3,
      container: waveformRef.current,
      backend: 'WebAudio',
      height: 30,
      barRadius: 3,
      responsive: true,
      progressColor: ['#26D1A8', '#AC4EFD', '#F1419E', '#FED503', '#FE5540'],
      waveColor: '#1C1B1B',
      barGap: 3,
      cursorColor: 'transparent',
    });

    wavesurfer.load(AudioElement);

    setWaver(wavesurfer);

    return () => wavesurfer.destroy();
  }, []);

  useEffect(() => {
    if (isPlaying && waver) waver.playPause();
  }, [isPlaying]);

  return (
    <div>
      <div ref={waveformRef} style={{ width: '225px', margin: '0 auto' }} />
    </div>
  );
};

// AUDIO ELEMENT

export const AudioElement = forwardRef<HTMLAudioElement, Props>((props, ref) => {
  const { className } = props;

  return <audio ref={ref} className={className} />;
});
0

There are 0 best solutions below