Audio files in Next.js

Viewed 20

I try to implement a local audio file in a next.js project. Thats not so easy as i mentioned, neither in the next.js docs or via web search i can find a working solution.

I tried the "react-audio-player" and "use-audio", but in both situations i have issues with referencing the audio file in the IDE. A audio html element is in the dom, but it doesnt work.

Is this a problem with the file-loader / how next.js handle it?

Someone know literature about it where i could look at or can give me a working example?

1 Answers
import { Box } from "@chakra-ui/react";
import type { NextComponentType } from "next";
import { useState, useEffect } from "react";
import Typewriter from "typewriter-effect";
const PlayIntro: NextComponentType = () => {
  const [playPause, setPlayPause] = useState(false);
  const [audioDom, setAdudioDom] = useState<HTMLAudioElement | null>(null);

  useEffect(() => {
    if (audioDom && playPause === true) {
      audioDom.play();
    }
    if (audioDom && playPause === false) {
      audioDom.pause();
    }

  }, [audioDom, playPause]);
  const IsplayMusic = () => {
    setPlayPause(!playPause);
  };

  return (
    <Box position="fixed" top={225} right={85}>
      <Box
        onClick={IsplayMusic}
        fontSize={"24px"}
        color={"#E2E2E2"}
        cursor="pointer"
      >
        {playPause === false ? (
          <Typewriter
            options={{
              strings: ["Play intro...", "Play intro..."],
              autoStart: true,
              loop: true,
            }}
          />
        ) : (
          <Typewriter
            options={{
              strings: ["Pause intro.", "Pause intro."],
              autoStart: true,
              loop: true,
            }}
          />
        )}
      </Box>

      <audio
        ref={(element) => setAdudioDom(element)}
        src="/playIntro.mp3"
      ></audio>
    </Box>
  );
};

export default PlayIntro;
Related