title: How can I play audio in background in Next.js?
body: <p>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:</p>
  <pre><code>const getCurrDuration = (e) =&gt; {
      const percent = ((e.currentTarget.currentTime / e.currentTarget.duration) * 100).toFixed(2)
      const time = e.currentTarget.currentTime
  
      setPercentage(+percent)
      setCurrentTime(time.toFixed(2))
  }
  
  const play = () =&gt; {
      const audio = audioRef.current
      if (typeof window !== &quot;undefined&quot;) {
          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 = () =&gt; {
      setIsPlaying(true)
      const audio = audioRef.current
      if (typeof window !== &quot;undefined&quot;) {
          audio.volume = localStorage.getItem('volume') ? localStorage.getItem('volume') : 1
          audio.playbackRate = localStorage.getItem('playbackRate') ? localStorage.getItem('playbackRate') : 1
      }
  
      if (router.query.time !== null &amp;&amp; router.query.time &gt; 0) {
          const audio = audioRef.current
  
          if (audio) {
              audio.currentTime = router.query.time
              setPercentage(router.query.time)
              setCurrentTime(router.query.time)
              setTimeIsFromUrl(false)
          }
      }
  }
  
  const stopPlaying = () =&gt; {
      setIsPlaying(false)
  }
  
  const onPlayingCapture = () =&gt; {
      const audio = audioRef.current
  
      if (currentTime &gt; 2) {
          localStorage.setItem(props.audio._id, currentTime)
      }
      if (props.time &gt; 0 &amp;&amp; props.time &lt;= duration) {
          audio.currentTime = props.time
  
          props.setTimeToZero()
      } else if (props.time &gt; 0 &amp;&amp; props.time &gt;= duration) {
          audio.currentTime = duration
  
          props.setTimeToZero()
      }
  }
  
   &lt;audio
      autoPlay={true}
      id=&quot;audio&quot;
      onPlay={startPlaying}
      ref={audioRef}
      onPlayingCapture={onPlayingCapture()}
      onPause={() =&gt; stopPlaying()}
      onTimeUpdate={getCurrDuration}
      src={props.audio.filePath}
      onLoadedData={(e) =&gt; {
         setDuration(e.currentTarget.duration.toFixed(2))
      }}
  /&gt;
  </code></pre>
  <p>My question is: How can I play audio in the background, despite the that the page is reloaded or left?</p>