How to use audio(MP3 files) in Next JS
Published by Debasish Gracias on 25 April 2021
Hello Friends,
Hope you all are well.
In this post we will learn how we can use audio(MP3 files) in Next JS. So let's get started.
First let's start by creating our next-app
npx create-next-app nextjs-audio
We are going to use the HTML <audio> element to play an audio file on a web page. More information on how to use the audio element in HTML can be found here.
Let's move forward by adding the audio MP3 file into our project. Then we need to add the audio element in our functional component like below:
import { useEffect, useState } from 'react'
export default function Home() {
const playlist = require('../public/audio/chlorine.mp3');
const [audioElement, setAudioElement] = useState(null);
const [playButton, setPlayButton] = useState(null);
useEffect(() => {
setAudioElement(document.querySelector("#myAudio"));
setPlayButton(document.querySelector('#playAudio'));
}, []);
const handleAudio = () => {
if (!playButton.classList.contains('isPlaying')) {
playButton.classList.add('isPlaying');
audioElement.setAttribute('src', playlist);
audioElement.play();
} else {
audioElement.pause();
playButton.classList.remove('isPlaying');
}
}
return (
<div className="main">
<audio id="myAudio">
Your browser does not support the audio element.
</audio>
<p>Click the button to play or pause the audio.</p>
<button className="btn" id="playAudio" onClick={handleAudio} type="button">Play Audio</button>
</div>
)
}
If we start the app now in development mode using the command npm run dev we will get the below error:
Failed to compile
./public/audio/chlorine.mp3 1:3
Module parse failed: Unexpected character '' (1:3)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
In order to fix the above issue we need to carry out the below two steps:
STEP 1: Add a custom loader to accept your .mp3 by installing file-loader for use in webpack using the below command:
npm install file-loader --save-dev
STEP 2: Create a new file next.config.js in the root of the project to handle .mp3 files correctly. Add the following piece of code into newly created next.config.js file
module.exports
={
webpack(config, options) {
config.module.rules.push({
test: /\.(mp3)$/,
use: {
loader: 'file-loader',
options: {
publicPath: '/_next/static/sounds/',
outputPath: 'static/sounds/',
name: '[name].[ext]',
esModule: false,
},
},
});
return config;
},
}
NOTE: Do remember to restart the server to see the changes in effect every time the next.config.js file is modified.
If we run the app now, it should be working as expected. Hurray! Now we know how to play an audio (.mp3) file in our Next JS app.