"use client" import { create } from "zustand" import { Podcast } from…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
"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
Great question!
The issue is how you manage the audioRef and the src assignment.
Every time you set a new src on an <audio> element, the browser resets the playback position to 0.
Your code sets audioRef.current.src = currentPodcast.audioUrl every time currentPodcast or isPlaying changes, which causes the audio to restart from the beginning even if it's the same podcast.
Only set the src when the podcast actually changes, not when play/pause is toggled.
audioRef.current.src on every isPlaying change.src only when the podcast changes.Audio object unless the podcast changes.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])
This runs on every isPlaying change, which is not what you want.
// Only run this effect when the podcast changes
useEffect(() => {
if (!currentPodcast?.audioUrl) return
if (!audioRef.current) {
audioRef.current = new Audio(currentPodcast.audioUrl)
} else {
audioRef.current.src = currentPodcast.audioUrl
}
audioRef.current.currentTime = 0 // Optionally reset to start on new podcast
// Optionally auto-play if isPlaying is true
if (isPlaying) {
audioRef.current.play().catch(console.error)
}
return () => {
audioRef.current?.pause()
}
}, [currentPodcast])
Now, for play/pause, just control the audio element:
useEffect(() => {
if (!audioRef.current) return
if (isPlaying) audioRef.current.play().catch(console.error)
else audioRef.current.pause()
}, [isPlaying])
audioRef.current.src when the podcast changes.src or create a new Audio object on every play/pause.const audioRef = useRef<HTMLAudioElement | null>(null)
useEffect(() => {
if (!currentPodcast?.audioUrl) return
if (!audioRef.current) {
audioRef.current = new Audio(currentPodcast.audioUrl)
} else {
audioRef.current.src = currentPodcast.audioUrl
}
audioRef.current.currentTime = 0 // reset to start on new podcast
if (isPlaying) {
audioRef.current.play().catch(console.error)
}
return () => {
audioRef.current?.pause()
}
}, [currentPodcast])
useEffect(() => {
if (!audioRef.current) return
if (isPlaying) audioRef.current.play().catch(console.error)
else audioRef.current.pause()
}, [isPlaying])
The bug is caused by setting the audio src on every play/pause.
Set the src only when the podcast changes, not when toggling play/pause.
Let me know if you want a full refactored component!