[SOLVED] Displaying audio waveforms in React

Issue

This Content is from Stack Overflow. Question asked by Stian Larsen

So i´m building this webpage which allow users to upload a song, and the displayind that sound as a card on the home-page. Sort of like Soundcloud…

Im just getting to learn React, after coming from html, css and JS. So please understand im new to this all.

I´ve been researched the topic alot, and no one has seemed to work for me.

Ive been trying howler.js, and wavesurfer.js, without any luck of displaying waveforms.

have anyone else tried doing this before? someone who could maybe help out?



Solution

The reference to the DOM element is accessed by the .current property Not the reference object created by React.

You could use the useEffect hook, to load the data.

Then create the AudioVisualizer Component in the JSX react way and pass the link to the wavesurfer.

Also the wavesurfer dom object need to have some size.

Have a look at this mini example:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { useRef, useEffect } from 'react';
import wavesurfer from 'wavesurfer.js'

const AudioVisualizer = (props) => {

  const audioRef = useRef();

  useEffect(()=>{
    if (audioRef.current){
      let audioTrack = wavesurfer.create({
          container: audioRef.current,
      });
      audioTrack.load(props.link);
    }
  })

  return <div style={{minWidth: "200px"}} className='audio' ref={audioRef}></div> 
}

function App(props) {
  return (
    <div className='App'>
      <AudioVisualizer link={"https://actions.google.com/sounds/v1/science_fiction/creature_distortion_white_noise.ogg"}></AudioVisualizer>
    </div>
  );
}

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(<App />)


This Question was asked in StackOverflow by Stian Larsen and Answered by ruff09 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?