Maxime Ghéraille
Maxime Ghéraille

Reputation: 1895

Audio is not defined when using nextjs

using this code keeps giving me the error ReferenceError: Audio is not defined. which I get because nextjs is ssr but there should be a way to make it work either way

  const musicPlayers = useRef<HTMLAudioElement>(
    new Audio("")
  );

I found online that I could use this thing

  const musicPlayers = useRef<false |HTMLAudioElement>(
    typeof Audio !== "undefined" && new Audio("")
  );

but then I need to use a false as possible option which gives me and error on the play pause code

Property 'paused' does not exist on type 'false | HTMLAudioElement'
Property 'play' does not exist on type 'false | HTMLAudioElement'.
     if (musicPlayers.current?.paused) {
          musicPlayers.current.play();
        } else {
          musicPlayers.current?.pause();
        }

Upvotes: 7

Views: 6742

Answers (1)

Replace:

const musicPlayers = useRef<HTMLAudioElement | undefined>(
  typeof Audio !== "undefined" ? new Audio("") : undefined
);

Then you can call:

musicPlayers.current?.play();
musicPlayers.current?.pause();

Upvotes: 7

Related Questions