"use client" import { create } from "zustand" import { Podcast } from…
- User
"use client"
import { create } from "zustand" import { Podcast } from "@/app/generated/prisma"
interface AudioPlayerState { isPlaying: boolean currentPodcast: Podcast | null playPodcast: (podcast: Podcast) => void pausePodcast: () => void togglePlayPause: () => void }
export const useAudioPlayer = create((set) => ({ isPlaying: false, currentPodcast: null, playPodcast: (podcast) => set({ isPlaying: true, currentPodcast: podcast }), pausePodcast: () => set({ isPlaying: false }), togglePlayPause: () => set((state) => ({ isPlaying: !state.isPlaying })), }))
"use client"
import { useAudioPlayer } from "@/hooks/use-audio-player" import { Play, Pause, SkipBack, SkipForward, Volume2, Calendar } from "lucide-react" import { Button } from "@/components/ui/button" import { Slider } from "@/components/ui/slider" import { useState, useEffect, useRef } from "react" import { formatPublishedDate } from "@/lib/utils"
export function AudioPlayer() { const { isPlaying, currentPodcast, togglePlayPause } = useAudioPlayer() const [progress, setProgress] = useState(0) const audioRef = useRef<HTMLAudioElement | null>(null)
const prevPodcastIdRef = useRef<string | null>(null)
useEffect(() => { if (!currentPodcast) { prevPodcastIdRef.current = null return } if (prevPodcastIdRef.current !== currentPodcast.id && audioRef.current) { audioRef.current.currentTime = 0
} prevPodcastIdRef.current = currentPodcast.id}, [currentPodcast])
useEffect(() => { if (!audioRef.current) return if (isPlaying) audioRef.current.play().catch(console.error) else audioRef.current.pause() }, [isPlaying])
useEffect(() => { if (currentPodcast) document.body.classList.add("player-active") return () => { document.body.classList.remove("player-active") } }, [currentPodcast])
useEffect(() => { if (currentPodcast?.audioUrl) { if (!audioRef.current) { audioRef.current = new Audio() }
audioRef.current.src = currentPodcast.audioUrl if (isPlaying) { audioRef.current.play().catch((err) => { console.error("Error playing audio:", err) }) } } return () => { audioRef.current?.pause() }}, [currentPodcast, isPlaying])
useEffect(() => { if (!audioRef.current) return if (isPlaying) audioRef.current.play().catch((err) => console.error(err)) else audioRef.current.pause() }, [isPlaying])
useEffect(() => { if (!audioRef.current) return const update = () => { const d = audioRef.current!.duration || 0 const t = audioRef.current!.currentTime || 0 setProgress((t / d) * 100) } audioRef.current.addEventListener("timeupdate", update) return () => audioRef.current!.removeEventListener("timeupdate", update) }, [currentPodcast])
if (!currentPodcast) return null
const handleSeek = (v: number[]) => { if (!audioRef.current) return const t = (v[0] / 100) * (audioRef.current.duration || 0) audioRef.current.currentTime = t setProgress(v[0]) }
return ( {currentPodcast.title} {formatPublishedDate(currentPodcast.publishedAt)}
<div className="flex flex-col items-center gap-2 flex-1 max-w-md mx-4"> <div className="flex items-center gap-4"> <Button size="icon" variant="ghost" className="text-white"> <SkipBack className="h-4 w-4" /> </Button> <Button size="icon" className="rounded-full bg-emerald-400 hover:bg-emerald-500 text-black" onClick={togglePlayPause} > {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />} </Button> <Button size="icon" variant="ghost" className="text-white"> <SkipForward className="h-4 w-4" /> </Button> </div> <div className="w-full flex items-center gap-2"> <span className="text-xs text-white/60">{formatTime(audioRef.current?.currentTime || 0)}</span> <Slider value={[progress]} max={100} step={0.1} className="flex-1" onValueChange={handleSeek} /> <span className="text-xs text-white/60">{currentPodcast.duration}</span> </div> </div> <div className="flex items-center gap-2 w-32"> <Volume2 className="h-4 w-4 text-white/60" /> <Slider defaultValue={[80]} max={100} step={1} className="flex-1" /> </div> </div> </div>) }
function formatTime(seconds: number): string { const mins = Math.floor(seconds / 60) const secs = Math.floor(seconds % 60) return
${mins}:${secs.toString().padStart(2, "0")}} The audio player restarts from the beginning when pressing pause and then play again. keep the state of where the audio is - Assistant
Here’s what’s happening:
Every time you toggle play/pause you’re re‑running the effect that sets
audioRef.current.src(because you includedisPlayingin that effect’s dependency array). Resettingsrcalways jumps you back to time 0.The fix is simple—split “load a new podcast” from “play/pause” into two separate effects:
-
One effect (deps:
[currentPodcast]) only runs when you switch episodes.- It creates your
<audio>once - It sets
srcand (optionally) resetscurrentTime = 0
- It creates your
-
A second effect (deps:
[isPlaying]) only runs when you hit play or pause.- It calls
.play()or.pause()on the existing audio element - It does not touch
src
- It calls
—> That way pausing/playing never resets the track.
Revised
AudioPlayer(key parts only)export function AudioPlayer() { const { isPlaying, currentPodcast, togglePlayPause } = useAudioPlayer() const [progress, setProgress] = useState(0) const audioRef = useRef<HTMLAudioElement | null>(null) const prevPodcastIdRef = useRef<string | null>(null) // 1) Initialize audio and load new src (only when podcast changes) useEffect(() => { if (!currentPodcast) return if (!audioRef.current) { audioRef.current = new Audio() } // load the new episode audioRef.current.src = currentPodcast.audioUrl audioRef.current.currentTime = 0 prevPodcastIdRef.current = currentPodcast.id // optional cleanup on unmount return () => { audioRef.current?.pause() } }, [currentPodcast]) // 2) Play / pause (only when `isPlaying` changes) useEffect(() => { if (!audioRef.current) return if (isPlaying) { audioRef.current.play().catch(console.error) } else { audioRef.current.pause() } }, [isPlaying]) // 3) Track progress useEffect(() => { if (!audioRef.current) return const update = () => { const d = audioRef.current!.duration || 0 const t = audioRef.current!.currentTime || 0 setProgress((t / d) * 100) } audioRef.current.addEventListener("timeupdate", update) return () => { audioRef.current!.removeEventListener("timeupdate", update) } }, [currentPodcast]) // …render your UI… }That way:
- Switching episodes ⇒ only effect #1 runs ⇒ you load a new
srcand reset to 0. - Toggling play/pause ⇒ only effect #2 runs ⇒ you
.play()or.pause(), but never touch thesrc/time. - Progress continues correctly across pauses.
Give that a try and your play/pause should now resume from wherever you left off! 🚀
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.