diff --git a/components/AudioPlayer.tsx b/components/AudioPlayer.tsx index 369af0f..72683d1 100644 --- a/components/AudioPlayer.tsx +++ b/components/AudioPlayer.tsx @@ -72,22 +72,30 @@ const AudioPlayer = forwardRef(({ src, unlocke if (autoPlay) { // Delay play slightly to ensure currentTime sticks setTimeout(() => { - const playPromise = audioRef.current?.play(); - if (playPromise !== undefined) { - playPromise - .then(() => { - setIsPlaying(true); - onPlay?.(); - setHasPlayedOnce(true); - onHasPlayedChange?.(true); // Notify parent - }) - .catch(error => { - console.log("Autoplay prevented:", error); - setIsPlaying(false); - }); + if (audioRef.current) { + // Ensure currentTime is set before playing + audioRef.current.currentTime = startTime; + const playPromise = audioRef.current.play(); + if (playPromise !== undefined) { + playPromise + .then(() => { + setIsPlaying(true); + onPlay?.(); + setHasPlayedOnce(true); + onHasPlayedChange?.(true); // Notify parent + }) + .catch(error => { + console.log("Autoplay prevented:", error); + setIsPlaying(false); + }); + } } }, 150); } + } else if (startTime !== undefined && audioRef.current.currentTime < startTime) { + // If startTime is set and currentTime is before it, reset to startTime + // This handles the case where the audio element was reset or reloaded + audioRef.current.currentTime = startTime; } } }, [src, unlockedSeconds, startTime, autoPlay, processedSrc, processedUnlockedSeconds]); @@ -97,6 +105,16 @@ const AudioPlayer = forwardRef(({ src, unlocke play: () => { if (!audioRef.current) return; + // Check if we need to reset to startTime + const current = audioRef.current.currentTime; + const elapsed = current - startTime; + + // Reset if: never played before, current position is before startTime, or we've exceeded the unlocked segment + if (!hasPlayedOnce || current < startTime || elapsed >= unlockedSeconds) { + // Reset to start of segment + audioRef.current.currentTime = startTime; + } + const playPromise = audioRef.current.play(); if (playPromise !== undefined) { playPromise @@ -121,8 +139,20 @@ const AudioPlayer = forwardRef(({ src, unlocke if (isPlaying) { audioRef.current.pause(); + setIsPlaying(false); } else { + // Check if we need to reset to startTime + const current = audioRef.current.currentTime; + const elapsed = current - startTime; + + // Reset if: never played before, current position is before startTime, or we've exceeded the unlocked segment + if (!hasPlayedOnce || current < startTime || elapsed >= unlockedSeconds) { + // Reset to start of segment + audioRef.current.currentTime = startTime; + } + audioRef.current.play(); + setIsPlaying(true); onPlay?.(); if (hasPlayedOnce) { @@ -132,7 +162,6 @@ const AudioPlayer = forwardRef(({ src, unlocke onHasPlayedChange?.(true); // Notify parent } } - setIsPlaying(!isPlaying); }; const handleTimeUpdate = () => {