How can I resolve the ReferenceError in NextJs which states that Audio is not defined?

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! 😊

Answer №1

To start, create the audio element in the HTML document using the <audio /> tag and set its style to display: none. Then, assign a reference to it as shown below:

"use client";

import { useState, useRef } from "react";

export default function BackgroundMusic() {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  const playBackgroundMusic = () => {
    if (!audioRef.current) return;

    if (!isPlaying) {
      setIsPlaying(true);
      audioRef.current.play();
    } else {
      setIsPlaying(false);
      audioRef.current.pause();
    }
  };

  return (
    <div className="w-8 fill-textBase active:scale-90s" onClick={() => playBackgroundMusic()} >
      <audio ref={audioRef} src="/audio/backgroundMusic.mp3" style={{ display: "none" }} />
      {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>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top method for transferring the result of a function to descendant components in Vue

In my parent component, I have a data object named config structured like this: data() { return { config: { Groups: [ { name: "A", Types: [ { mask: 1234, name: ...

What separates the act of declaring a generic function from explicitly declaring a type for that very same generic function?

Here are two instances demonstrating the use of a generic function: function myGenericFunction<TFunc extends Function>(target:TFunc): string { return target.toString(); } Based on this response, this represents a declaration for a generic funct ...

I am experiencing difficulty in passing parameters to nested navigators

I have developed a TechInfo page and a ProfileInfo page. The ProfileInfo Page is nested inside a Drawer Navigator. I want to display some information from the TechInfo page and some from the ProfileInfo page when I enter our info and press a button. Howeve ...

Disabling multiple textboxes in an array when any one of them has a value entered

Is there a way to automatically disable all text boxes if any one of them has a value? I have an array of cost types and their associated costs. If a cost is entered for any type, all other text boxes for cost types should be disabled. If no cost is ente ...

Guide on applying CSS to option tag within a select element in VUE.js

I am attempting to design a dropdown menu that resembles the one shown in the image. However, I'm currently unable to include any CSS styling. Can anyone provide guidance on how to create a customizable select dropdown in Vue? https://i.stack.imgur.c ...

What is the best way to select the destination folder for output in Webpack?

Whenever I run webpack using "webpack --mode development", it generates a dist folder and places the bundle.js file inside it. My aim is to have it created and placed in the same directory instead. How can I achieve this? module.exports = { entry: " ...

What is the best way to extract a specific line from a command using a child process in a Node.js environment?

I am attempting to retrieve the disk space of a virtual machine using a child process in Node.js. Below is the code I have written for this purpose: const { exec } = require('child_process'); function diskSpace(err, result) { exec('df - ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Are you wondering about the correct way to install eslint-config-airbnb without encountering any "UNMET PEER DEPENDENCY"

➜ beslint git:(master) ✗ eslint -v v3.15.0 ➜ beslint git:(master) ✗ npm install -g eslint-config-airbnb eslint-plugin-jsx-a11y eslint-plugin-import eslint-plugin-react /Users/next/.nvm/versions/node/v7.5.0/lib ├── UNM ...

XPathSelectorError: The provided xpath expression is invalid and unable to locate the specified element

Here is an HTML snippet element: <a ng-click="nodes.setViewType('tiles',true)"> <span class="fa fa-check Tick-Inactive" ng-class="nodes.viewType == 'tiles'? 'Tick-Active':'Tick-Inactive'" style="">< ...

The custom tab component in React is currently not accepting the "disabledTabs" prop

I have designed a tab component as shown below: tab/index.jsx import React from 'react'; import TabHeader from './header'; import TabBody from './body'; import TabHeaderList from './header/list'; import TabBodyList ...

Leveraging JSON to access arrays in React

In my current structure, I have: const [res, setRes] = useState({ question: "", option: [, , , ,], answer: 0, }); I am looking to update the values in the option array based on their indices. For example, setting option[3] to 2 ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

How can I access an InputStream from a local XML file in a PhoneGap application?

Looking for advice on how to fetch an inputstream from a local XML file using JavaScript in my PhoneGap application. I'm new to JavaScript, so any guidance would be appreciated! ...

What is the best method for organizing data in rows and columns?

I attempted to use my map function to iterate over the data and display it, but I struggled to format it into rows and columns. The requirement is for 5 fixed columns with dynamically changing rows, making array indexing impractical. Here is the code snip ...

What's the best way to implement satisfies with a generic type?

In my development process, I am working with components that have default values combined with props. To streamline this process, I created a single function for all components: export function getAssignProps <T extends {}>(propsMass:T[]){ return ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Removing duplicate data from Table TD and TR elements using Jquery

I am working on an HTML table and I need to remove duplicate values in each <tr> and <td> data cell. Here is a snippet of my code: <table width="100%" id="l2table"> <thead><tr> ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Using AJAX to showcase data from a table in a database using the <select> tag but with an unfinished submit process

I am encountering an issue with my code. When I submit the value in getinv.php, it only returns a partial value. For example, when I click '2016-08-27', it only retrieves '2016'... My question is, how can I ensure that the exact value ...