diff --git a/components/WaveformEditor.tsx b/components/WaveformEditor.tsx index 1b59adb..972ef7a 100644 --- a/components/WaveformEditor.tsx +++ b/components/WaveformEditor.tsx @@ -187,15 +187,30 @@ export default function WaveformEditor({ audioUrl, startTime, duration, unlockSt } }; - const updatePlaybackPosition = () => { - if (!audioContextRef.current || !isPlaying) return; + // Animation loop for playback cursor + useEffect(() => { + if (!isPlaying || !audioContextRef.current) { + return; + } - const elapsed = audioContextRef.current.currentTime - playbackStartTimeRef.current; - const currentPos = playbackOffsetRef.current + elapsed; - setPlaybackPosition(currentPos); + const animate = () => { + if (!audioContextRef.current || !isPlaying) return; - animationFrameRef.current = requestAnimationFrame(updatePlaybackPosition); - }; + const elapsed = audioContextRef.current.currentTime - playbackStartTimeRef.current; + const currentPos = playbackOffsetRef.current + elapsed; + setPlaybackPosition(currentPos); + + animationFrameRef.current = requestAnimationFrame(animate); + }; + + animationFrameRef.current = requestAnimationFrame(animate); + + return () => { + if (animationFrameRef.current) { + cancelAnimationFrame(animationFrameRef.current); + } + }; + }, [isPlaying]); const handlePlaySegment = (segmentIndex: number) => { if (!audioBuffer || !audioContextRef.current) return; @@ -219,8 +234,6 @@ export default function WaveformEditor({ audioUrl, startTime, duration, unlockSt setPlayingSegment(segmentIndex); setPlaybackPosition(segmentStart); - animationFrameRef.current = requestAnimationFrame(updatePlaybackPosition); - source.onended = () => { setIsPlaying(false); setPlayingSegment(null); @@ -250,8 +263,6 @@ export default function WaveformEditor({ audioUrl, startTime, duration, unlockSt setIsPlaying(true); setPlaybackPosition(startTime); - animationFrameRef.current = requestAnimationFrame(updatePlaybackPosition); - source.onended = () => { setIsPlaying(false); setPlaybackPosition(null);