<- Go Back

How to play music on Nextjs App-router

8 min read
How to play music in nextjs

Hi there๐Ÿ‘‹, in this blog post, you'll learn how to create a simple music player in a Next.js application using the Audio API. We'll leverage the Next.js App Router and client-side rendering to ensure audio functionality works seamlessly.We're using the NextJS App-router so by default everything written in code will be rendered server-side

Understanding Client-Side Components:

Next.js offers use client directive. which indicates that the component should only be rendered on the client-side (in the browser). This is essential for audio playback because browser Audio APIs, like the object, are not directly accessible during server-side rendering

"use client";

import React, { useState, useEffect } from "react";

const MusicPlayer = () => {

const [song, setSong] = useState<HTMLAudioElement | null>(null);

// Set up the audio element on component mount (client-side)

useEffect(() => {
   if (typeof window !== "undefined") {
   // Assuming song.mp3 exists in the public folder
   setSong(new Audio("/sounds/song.mp3"));
   }
}, []);

// on button click we're playing the music
const playMusic = () => {
   if (song) song.play();
};

return <button onClick={playMusic}>Play</button>
}

Bonus: Controlling Audio Playback

  • You can handle the volume and change the playtime by using these methods

  const playMusic = () => {
     if (song) {
       // Set volume to 50%
       addSound.volume = 0.5;

       // Start playback from the 19th second
       addSound.currentTime = 19;
       song.play();
    }
};

  • While the built-in Audio API is sufficient for basic audio playback, libraries like use-sound (https://www.npmjs.com/package/use-sound) can offer additional features and simplification. Explore these libraries if your application's audio requirements become more complex. However, be mindful of potential build-time issues and ensure compatibility with your project's setup.

Thank youโœŒ๏ธ, happy coding!

Share:

๐Ÿ”” Subscribe to our Newsletter

Stay up to date with our latest news and products

contentql logoMade in ContentQL