I have a Next.js project. I have an audio player, but when the page is left or reloaded audio stops playing. How can I make an audio play in the background? I thought iframe would be a great fit, but it asks me where I want to download my audio. Here's the player I have now:
const getCurrDuration = (e) => {
const percent = ((e.currentTarget.currentTime / e.currentTarget.duration) * 100).toFixed(2)
const time = e.currentTarget.currentTime
setPercentage(+percent)
setCurrentTime(time.toFixed(2))
}
const play = () => {
const audio = audioRef.current
if (typeof window !== "undefined") {
audio.volume = localStorage.getItem('volume') ? localStorage.getItem('volume') : 1
audio.playbackRate = localStorage.getItem('playbackRate') ? localStorage.getItem('playbackRate') : 1
if (!isPlaying) {
setIsPlaying(true)
audio.play()
}
if (isPlaying) {
setIsPlaying(false)
audio.pause()
}
}
}
const startPlaying = () => {
setIsPlaying(true)
const audio = audioRef.current
if (typeof window !== "undefined") {
audio.volume = localStorage.getItem('volume') ? localStorage.getItem('volume') : 1
audio.playbackRate = localStorage.getItem('playbackRate') ? localStorage.getItem('playbackRate') : 1
}
if (router.query.time !== null && router.query.time > 0) {
const audio = audioRef.current
if (audio) {
audio.currentTime = router.query.time
setPercentage(router.query.time)
setCurrentTime(router.query.time)
setTimeIsFromUrl(false)
}
}
}
const stopPlaying = () => {
setIsPlaying(false)
}
const onPlayingCapture = () => {
const audio = audioRef.current
if (currentTime > 2) {
localStorage.setItem(props.audio._id, currentTime)
}
if (props.time > 0 && props.time <= duration) {
audio.currentTime = props.time
props.setTimeToZero()
} else if (props.time > 0 && props.time >= duration) {
audio.currentTime = duration
props.setTimeToZero()
}
}
<audio
autoPlay={true}
id="audio"
onPlay={startPlaying}
ref={audioRef}
onPlayingCapture={onPlayingCapture()}
onPause={() => stopPlaying()}
onTimeUpdate={getCurrDuration}
src={props.audio.filePath}
onLoadedData={(e) => {
setDuration(e.currentTarget.duration.toFixed(2))
}}
/>
My question is: How can I play audio in the background, despite the that the page is reloaded or left?