Reputation: 333
I have this instance of wavesurfer ni one of my projects. This displays various audio files dynamically. I'm rendering this on a page where i want play and pause buttons to trigger wave surfer.
I don't quite understand how i can pass these functions?
THey are marked in the code.
THanks in advance!
export default function FiddleDisplay({ audioFileUrl }) {
const waveformRef = React.useRef();
React.useEffect(() => {
if (waveformRef.current) {
const activeWaveColor = '#f5f5f5';
const playedWaveColor = '#707070';
const wavesurfer = WaveSurfer.create({
container: waveformRef.current,
barWidth: 5,
cursorWidth: 2,
waveColor: activeWaveColor,
progressColor: playedWaveColor,
hideScrollbar: true,
autoCenter: false,
responsive: true,
width: 100,
barHeight: 9,
height: 350,
interact: true,
maxCanvasWidth: 2000,
fillParent: true
});
wavesurfer.load(`${audioFileUrl}`);
wavesurfer.play(); //USE THIS IN OTHER COMPONENT
wavesurfer.pause(); //USE THIS IN OTHER COMPONENT
}
}, []);
return (
<>
<Waveform ref={waveformRef} />
</>
);
}
Upvotes: 3
Views: 6690
Reputation: 22030
You'll want to store the reference to the instance with useState, and attach the relevant bound methods to buttons:
export default function FiddleDisplay({
audioFileUrl,
}) {
const waveformRef = React.useRef();
const [waveSurfer, setWaveSurfer] = React.useState();
React.useEffect(() => {
if (waveformRef.current) {
const activeWaveColor = '#f5f5f5';
const playedWaveColor = '#707070';
const wavesurfer = WaveSurfer.create({
container: waveformRef.current,
barWidth: 5,
cursorWidth: 2,
waveColor: activeWaveColor,
progressColor: playedWaveColor,
hideScrollbar: true,
autoCenter: false,
responsive: true,
width: 100,
barHeight: 9,
height: 350,
interact: true,
maxCanvasWidth: 2000,
fillParent: true
});
wavesurfer.load(`${audioFileUrl}`);
setWaveSurfer(wavesurfer);
}
}, []);
const play = waveSurfer && waveSurfer.play.bind(waveSurfer);
const pause = waveSurfer && waveSurfer.pause.bind(waveSurfer);
return (
<>
<Waveform ref={waveformRef} />
<Button onClick={play}>Play</Button>
<Button onClick={pause}>Pause</Button>
</>
);
}
If you want to render the buttons somewhere else, you'll need to pass in a setter from a parent function and pass the bound methods back up.
Upvotes: 2