this is my first time posting ere, I hope I'm doing it correctly.
I'm working on an audio player component in React. The component has a progress bar, and I'm trying to update the currentTime
of the audio when the user clicks or drags on the progress bar. However, whenever I try to set the currentTime
, it resets to 0 instead of the desired value. I've tried different approaches, but the issue persists.
i'm using React + TypeScript.
Here is the code that causing me the issue :
- The
useRef
that is linked to my<audio>
element:
const audioRef = useRef<HTMLAudioElement>(null);
- The
handleMouseDown
function that doesn't work as expected:
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement, MouseEvent>): void => {
if (audioRef.current) {
// Pause the audio while modifying
audioRef.current.pause();
setIsPlaying(false);
const width = progressRef.current!.clientWidth;
const clickX = e.nativeEvent.offsetX;
const duration = audioRef.current.duration;
let newTime = (clickX / width) * duration;
// Set the width of the progress bar
setProgress((newTime / duration) * 100);
// Listen to "mousemove" and "mouseup" events to set the width of the progress bar while the mouse moves
const handleMouseMove = (e: MouseEvent) => {
const newX = e.clientX - progressRef.current!.getBoundingClientRect().left;
newTime = (newX / width) * duration;
setProgress((newTime / duration) * 100);
};
const handleMouseUp = () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
console.log(newTime); // Logs the correct value
audioRef.current!.currentTime = newTime;
audioRef.current!.play().then(() => setIsPlaying(true));
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);
}
};
The problem occurs in the handleMouseUp
function when I try to set audioRef.current!.currentTime
. Even though console.log(newTime)
logs the correct value, the currentTime
resets to 0.
the entire code can be found to my github : Full component code
I should mention that I am a beginner in programming, so I apologize if the solution seems obvious to you, but I am completely stuck.