Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
like image 916
Maxime Ghéraille Avatar asked Aug 01 '26 01:08

Maxime Ghéraille


1 Answers

Replace:

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

Then you can call:

musicPlayers.current?.play();
musicPlayers.current?.pause();
like image 102
Johann-Michael Thiebaut Avatar answered Aug 02 '26 17:08

Johann-Michael Thiebaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!