Recently, I implemented a Next component that acts as a music player, allowing users to play or stop the audio just like an MP3 player. While the functionality works perfectly fine on my local server – clicking the button triggers the audio play or pause – I encountered an error in the terminal that reads:
src\components\bgmAudio.tsx (6:31) @ Audio
⨯ ReferenceError: Audio is not defined
at BgmAudio (./src/components/bgmAudio.tsx:13:72)
digest: "2253870762"
4 | export default function BgmAudio() {
5 | const [isPlaying, setIsPlaying] = useState(false);
> 6 | const audioRef = useRef(new Audio("/audio/bgmAmbient.MP3"));
| ^
Below is the complete source code I have:
"use client";
import { useEffect, useState, useRef } from "react";
export default function BgmAudio() {
const [isPlaying, setIsPlaying] = useState(false);
const audioRef = useRef(new Audio("/audio/bgmAmbient.MP3"));
const bgmPlay = () => {
if (!isPlaying) {
setIsPlaying(true);
audioRef.current.play();
} else {
setIsPlaying(false);
audioRef.current.pause();
}
};
return (
// Button to play or stop the audio
<div className="w-8 fill-textBase active:scale-90s" onClick={() => bgmPlay()}>
{isPlaying && (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
</svg>
)}
{!isPlaying && (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
</svg>
)}
</div>
);
}
Any suggestions on how to address this issue? I'm using Typescript, by the way! 😊