
How to play music on Nextjs App-router
How to play songs using Nextjs App-router without using any packages
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
const playMusic = () => { if (song) { // Set volume to 50% addSound.volume = 0.5; // Start playback from the 19th second addSound.currentTime = 19; song.play(); } };
Thank you✌️, happy coding!