Files
encoach_frontend/src/components/Waveform.tsx
2023-06-15 16:35:30 +01:00

73 lines
1.6 KiB
TypeScript

import React, {useEffect, useRef, useState} from "react";
import {BsPauseFill, BsPlayFill} from "react-icons/bs";
import WaveSurfer from "wavesurfer.js";
interface Props {
audio: string;
waveColor: string;
progressColor: string;
}
const Waveform = ({audio, waveColor, progressColor}: Props) => {
const containerRef = useRef(null);
const waveSurferRef = useRef<WaveSurfer | null>();
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {
const waveSurfer = WaveSurfer.create({
container: containerRef?.current || "",
responsive: true,
cursorWidth: 0,
height: 24,
waveColor,
progressColor,
barGap: 5,
barWidth: 8,
barRadius: 4,
fillParent: true,
hideScrollbar: true,
normalize: true,
autoCenter: true,
ignoreSilenceMode: true,
barMinHeight: 4,
});
waveSurfer.load(audio);
waveSurfer.on("ready", () => {
waveSurferRef.current = waveSurfer;
});
waveSurfer.on("finish", () => setIsPlaying(false));
return () => {
waveSurfer.destroy();
};
}, [audio, progressColor, waveColor]);
return (
<>
{isPlaying && (
<BsPauseFill
className="text-mti-gray-cool cursor-pointer w-5 h-5"
onClick={() => {
setIsPlaying((prev) => !prev);
waveSurferRef.current?.playPause();
}}
/>
)}
{!isPlaying && (
<BsPlayFill
className="text-mti-gray-cool cursor-pointer w-5 h-5"
onClick={() => {
setIsPlaying((prev) => !prev);
waveSurferRef.current?.playPause();
}}
/>
)}
<div className="w-full max-w-4xl h-fit" ref={containerRef} />
</>
);
};
export default Waveform;