Introduction
हेलो दोस्तों आज हम इस post में HTML और javascript का इस्तेमाल करके एक music player create करेंगे!. जिसमे हम song को next, preview button और play and pause button साथ में song progress bar और volume का setting बी रखेंगे साथ में हम music player का background color automally change होता रहे ऐसी functionality setup करेंगे और इस music player को example से साथ code का explaination detail के साथ समझेंगे।
Create a music player with HTML and Javascript
HTML code
HTML का इस्तेमाल करके हमने music player का एक structure ready किया है!.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" /> </head> <body> <div class="music-player" id="bgImage"> <div id="parent"> <div id="child"> <h2 class="main-title">Create Music Player Using Javascript</h2> <div class="player"> <div class="song-info"> <div id="song-title">Song Title</div> <div id="song-artist">Song Artist</div> </div> <div class="player-controls"> <div class="progress"> <div class="total-range">0:00</div> <input type="range" id="songRange" min="0" max="100" step="1" value="0"> <div class="current-range">0:00</div> </div> <div class=""> <button id="prev-btn" class="control-btn"><i class="fa-solid fa-backward"></i></button> <button id="play-btn" class="control-btn"><i class="fa-solid fa-play"></i></button> <button id="next-btn" class="control-btn"><i class="fa-solid fa-forward"></i></button> </div> <div> <span id="volumeIcon"><i class="fa-solid fa-volume-high"></i></span> <input type="range" id="volumeControl" min="0" max="1" step="0.1" value="1"> </div> </div> </div> <div class="playlist"> <h2>Playlist</h2> <ul id="playlist-list"></ul> </div> </div> </div> </div> </body> </html>
Javascript code
<script> const audio = new Audio(); let currentSongIndex = 0; const playlist = [ { title: "Song 1", artist: "Artist 1", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-1.mp3", bgimg : "file:///C:/Users/gamit/Downloads/music-sound-multimedia-player-concept.jpg", }, { title: "Song 01", artist: "Artist 01", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-2.mp3", bgimg : "file:///C:/Users/gamit/Downloads/smiling-women-listening-music.jpg", }, { title: "Song 3", artist: "Artist 3", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-3.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, { title: "Song 4", artist: "Artist 4", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-4.mp3", bgimg : "file:///C:/Users/gamit/Downloads/smiling-women-listening-music.jpg", }, { title: "Song 5", artist: "Artist 5", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-5.mp3", bgimg : "file:///C:/Users/gamit/Downloads/music-sound-multimedia-player-concept.jpg", }, { title: "Song 6", artist: "Artist 6", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-6.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, { title: "Song 2", artist: "Artist 2", source: "https://www.computerhope.com/jargon/m/example.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, // Add more songs to the playlist ]; const playBtn = document.getElementById("play-btn"); const prevBtn = document.getElementById("prev-btn"); const nextBtn = document.getElementById("next-btn"); const songTitle = document.getElementById("song-title"); const songArtist = document.getElementById("song-artist"); const playlistList = document.getElementById("playlist-list"); const volumeBtn = document.getElementById("volumeControl"); const songRange = document.getElementById("songRange"); const bgImage = document.getElementById("bgImage"); const volumeIcon = document.getElementById("volumeIcon"); const totalRange = document.querySelector('.total-range'); const currentRange = document.querySelector('.current-range'); const parentElement = document.getElementById('parent'); const childElement = document.getElementById('child'); function loadSong(songIndex) { console.log(songIndex); const song = playlist[songIndex]; audio.src = song.source; songTitle.textContent = song.title; songArtist.textContent = song.artist; updatePlaylistUI(songIndex); const imageUrl = song.bgimg; //bgImage.style.backgroundImage = `url('${imageUrl}')`; } function playPause() { if (audio.paused) { audio.play(); playBtn.innerHTML = '<i class="fa-solid fa-pause"></i>'; } else { audio.pause(); playBtn.innerHTML = '<i class="fa-solid fa-play"></i>'; } } function playNextSong() { currentSongIndex = (currentSongIndex + 1) % playlist.length; loadSong(currentSongIndex); audio.play(); } function playPrevSong() { currentSongIndex = (currentSongIndex - 1 + playlist.length) % playlist.length; loadSong(currentSongIndex); audio.play(); } function updatePlaylistUI(inx) { playlistList.innerHTML = ""; playlist.forEach((song, index) => { const li = document.createElement("li"); li.textContent = `${song.title} - ${song.artist}`; li.addEventListener("click", () => { currentSongIndex = index; loadSong(currentSongIndex); audio.play(); updatePlaylistUI(currentSongIndex); }); if (index === inx) { li.classList.add("active"); } playlistList.appendChild(li); }); } function volumeControl(){ audio.volume = volumeBtn.value; updateVolumeIcon(); } function songProgressbar(){ const progress = (audio.currentTime / audio.duration) * 100; songRange.value = progress; const currentTime = audio.currentTime; currentRange.textContent = formatTime(currentTime); songRange.value = currentTime; } function getRandomColor() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); return `rgb(${r},${g},${b})`; } function changeColors() { const parentColor = getRandomColor(); const childColor = getRandomColor(); // Set the background color for the parent element parentElement.style.backgroundColor = parentColor; // Set the background color for the child element childElement.style.backgroundColor = childColor; // If the colors match, call the function again to get new colors if (parentColor === childColor) { changeColors(); } } function updateVolumeIcon(){ const volume = audio.volume; console.log( volume ); if (volume === 0) { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-xmark"></i>'; } else if (volume < 0.5) { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-low"></i>'; } // else if ( volume >= 0.5 && volume < 0.8) { // volumeIcon.innerHTML = '<i class="fa-solid fa-volume"></i>'; // } else { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-high"></i>'; } } function formatTime(timeInSeconds) { const minutes = Math.floor(timeInSeconds / 60); const seconds = Math.floor(timeInSeconds % 60); return `${minutes}:${seconds.toString().padStart(2, '0')}`; } function songRangeUpdate(){ const currentTime = (audio.duration * songRange.value) / 100; audio.currentTime = currentTime; } function loadedmetadata() { const totalDuration = audio.duration; totalRange.textContent = formatTime(totalDuration); songRange.max = totalDuration; }; setInterval(function() { changeColors(); }, 3000); audio.addEventListener("ended", playNextSong); audio.addEventListener('loadedmetadata', loadedmetadata); playBtn.addEventListener("click", playPause); nextBtn.addEventListener("click", playNextSong); prevBtn.addEventListener("click", playPrevSong); volumeBtn.addEventListener("input", volumeControl); audio.addEventListener("timeupdate", songProgressbar); songRange.addEventListener("input", songRangeUpdate); updatePlaylistUI(); loadSong(currentSongIndex); </script>
ऊपर में दिए गये Javascript code में देख सकते है की javascript में new Audio() एक constructor function है! जिसका इस्तेमाल HTML5 Audio object create करने के लिए किया जाता है!. यह Audio object web audio API का हिस्सा है और यह आपको browser में audio के साथ काम करने की अनुमति देता है!. तो इस audio object के इस्तेमाल करके song को play करना, stop करना साथ ही song को next और preview या song का volume कम या बढ़ाना जैसे song के control हम audio
object के मदद से करेंगे!.
Music player में song को manage करने के लिए हमने कई function create किये है जिससे की हम song का pura control कर सके जैसे ही हमारा document load होगा तो loadSong() नाम का function load होगा और उसमे हमारे songs playlists में से first index में जो song listed होगा वह setup होगा उसके बाद में playPause() function है जो हम play button पे click करने पर song start होगा और puase button पर click करने पर song stop होगा ये सब behaviour हमारा playPause() function से manage होगा!.
playNextSong() function songs play list में next song को play करने के लिए है और playPrevSong() function songs play list से preview song को play करने के लिए है!.
Play lists के songs के volume को manage करने के लिए volumeControl() function है जो songs के volume को increase और decrease में manage करता है!.
उसके बाद में music player का background color automatically change करने के लिए हमने setInterval() function का इस्तेमाल किया जो हर 3 second के bad changeColors() name का function को execute करेगा और इस function के अंडर बी एक और getRandomColor() function execute होंगे जो हमें एक random color provide करता है!.
और ये provided color से हम हमारे music player का background color setup करेंगे!.
CSS code
<style> body{ margin: 0px; } .music-player { max-width: 100%; width: 100%; background-repeat: no-repeat; background-size: cover; } .player { margin-bottom: 20px; } .player-controls .control-btn { font-size: 16px; padding: 10px 20px; background-color: #007bff; color: #fff;border: none; border-radius: 5px; cursor: pointer; margin: 0 5px; } .song-info { margin-top: 10px; font-size: 18px; } .playlist { text-align: left; } .playlist h2 { font-size: 20px; } #playlist-list { list-style: none; padding: 0; } #playlist-list li { padding: 5px 0; cursor: pointer; } #playlist-list li.active { color: #007bff; font-weight: bold;} #parent { padding: 50px; } #child { width: 700px; margin: 0 auto; padding: 50px; border-radius: 15px; } .player-controls { display: flex; justify-content: center; align-items: center; } .progress { display: flex; justify-content: space-between; } #song-artist { margin-left: 20px; } #song-title { margin-right: 20px; } .song-info { display: flex; justify-content: center; margin-bottom: 35px; } h2.main-title{ text-align: center; margin-bottom: 50px;} </style>
Full source code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" /> </head> <style> body{ margin: 0px; } .music-player { max-width: 100%; width: 100%; background-repeat: no-repeat; background-size: cover; } .player { margin-bottom: 20px; } .player-controls .control-btn { font-size: 16px; padding: 10px 20px; background-color: #007bff; color: #fff;border: none; border-radius: 5px; cursor: pointer; margin: 0 5px; } .song-info { margin-top: 10px; font-size: 18px; } .playlist { text-align: left; } .playlist h2 { font-size: 20px; } #playlist-list { list-style: none; padding: 0; } #playlist-list li { padding: 5px 0; cursor: pointer; } #playlist-list li.active { color: #007bff; font-weight: bold;} #parent { padding: 50px; } #child { width: 700px; margin: 0 auto; padding: 50px; border-radius: 15px; } .player-controls { display: flex; justify-content: center; align-items: center; } .progress { display: flex; justify-content: space-between; } #song-artist { margin-left: 20px; } #song-title { margin-right: 20px; } .song-info { display: flex; justify-content: center; margin-bottom: 35px; } h2.main-title{ text-align: center; margin-bottom: 50px;} </style> <body> <div class="music-player" id="bgImage"> <div id="parent"> <div id="child"> <h2 class="main-title">Create Music Player Using Javascript</h2> <div class="player"> <div class="song-info"> <div id="song-title">Song Title</div> <div id="song-artist">Song Artist</div> </div> <div class="player-controls"> <div class="progress"> <div class="total-range">0:00</div> <input type="range" id="songRange" min="0" max="100" step="1" value="0"> <div class="current-range">0:00</div> </div> <div class=""> <button id="prev-btn" class="control-btn"><i class="fa-solid fa-backward"></i></button> <button id="play-btn" class="control-btn"><i class="fa-solid fa-play"></i></button> <button id="next-btn" class="control-btn"><i class="fa-solid fa-forward"></i></button> </div> <div> <span id="volumeIcon"><i class="fa-solid fa-volume-high"></i></span> <input type="range" id="volumeControl" min="0" max="1" step="0.1" value="1"> </div> </div> </div> <div class="playlist"> <h2>Playlist</h2> <ul id="playlist-list"></ul> </div> </div> </div> </div> <script> const audio = new Audio(); let currentSongIndex = 0; const playlist = [ { title: "Song 1", artist: "Artist 1", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-1.mp3", bgimg : "file:///C:/Users/gamit/Downloads/music-sound-multimedia-player-concept.jpg", }, { title: "Song 01", artist: "Artist 01", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-2.mp3", bgimg : "file:///C:/Users/gamit/Downloads/smiling-women-listening-music.jpg", }, { title: "Song 3", artist: "Artist 3", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-3.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, { title: "Song 4", artist: "Artist 4", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-4.mp3", bgimg : "file:///C:/Users/gamit/Downloads/smiling-women-listening-music.jpg", }, { title: "Song 5", artist: "Artist 5", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-5.mp3", bgimg : "file:///C:/Users/gamit/Downloads/music-sound-multimedia-player-concept.jpg", }, { title: "Song 6", artist: "Artist 6", source: "file:///C:/Users/gamit/Downloads/Playlist%20-%20Singer-songwriter%20-%20500608899%20---%20Jamendo%20-%20MP3/track-6.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, { title: "Song 2", artist: "Artist 2", source: "https://www.computerhope.com/jargon/m/example.mp3", bgimg : "file:///C:/Users/gamit/Downloads/young-woman-listening-music-headphones-her-friend.jpg", }, // Add more songs to the playlist ]; const playBtn = document.getElementById("play-btn"); const prevBtn = document.getElementById("prev-btn"); const nextBtn = document.getElementById("next-btn"); const songTitle = document.getElementById("song-title"); const songArtist = document.getElementById("song-artist"); const playlistList = document.getElementById("playlist-list"); const volumeBtn = document.getElementById("volumeControl"); const songRange = document.getElementById("songRange"); const bgImage = document.getElementById("bgImage"); const volumeIcon = document.getElementById("volumeIcon"); const totalRange = document.querySelector('.total-range'); const currentRange = document.querySelector('.current-range'); const parentElement = document.getElementById('parent'); const childElement = document.getElementById('child'); function loadSong(songIndex) { console.log(songIndex); const song = playlist[songIndex]; audio.src = song.source; songTitle.textContent = song.title; songArtist.textContent = song.artist; updatePlaylistUI(songIndex); const imageUrl = song.bgimg; //bgImage.style.backgroundImage = `url('${imageUrl}')`; } function playPause() { if (audio.paused) { audio.play(); playBtn.innerHTML = '<i class="fa-solid fa-pause"></i>'; } else { audio.pause(); playBtn.innerHTML = '<i class="fa-solid fa-play"></i>'; } } function playNextSong() { currentSongIndex = (currentSongIndex + 1) % playlist.length; loadSong(currentSongIndex); audio.play(); } function playPrevSong() { currentSongIndex = (currentSongIndex - 1 + playlist.length) % playlist.length; loadSong(currentSongIndex); audio.play(); } function updatePlaylistUI(inx) { playlistList.innerHTML = ""; playlist.forEach((song, index) => { const li = document.createElement("li"); li.textContent = `${song.title} - ${song.artist}`; li.addEventListener("click", () => { currentSongIndex = index; loadSong(currentSongIndex); audio.play(); updatePlaylistUI(currentSongIndex); }); if (index === inx) { li.classList.add("active"); } playlistList.appendChild(li); }); } function volumeControl(){ audio.volume = volumeBtn.value; updateVolumeIcon(); } function songProgressbar(){ const progress = (audio.currentTime / audio.duration) * 100; songRange.value = progress; const currentTime = audio.currentTime; currentRange.textContent = formatTime(currentTime); songRange.value = currentTime; } function getRandomColor() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); return `rgb(${r},${g},${b})`; } function changeColors() { const parentColor = getRandomColor(); const childColor = getRandomColor(); // Set the background color for the parent element parentElement.style.backgroundColor = parentColor; // Set the background color for the child element childElement.style.backgroundColor = childColor; // If the colors match, call the function again to get new colors if (parentColor === childColor) { changeColors(); } } function updateVolumeIcon(){ const volume = audio.volume; console.log( volume ); if (volume === 0) { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-xmark"></i>'; } else if (volume < 0.5) { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-low"></i>'; } // else if ( volume >= 0.5 && volume < 0.8) { // volumeIcon.innerHTML = '<i class="fa-solid fa-volume"></i>'; // } else { volumeIcon.innerHTML = '<i class="fa-solid fa-volume-high"></i>'; } } function formatTime(timeInSeconds) { const minutes = Math.floor(timeInSeconds / 60); const seconds = Math.floor(timeInSeconds % 60); return `${minutes}:${seconds.toString().padStart(2, '0')}`; } function songRangeUpdate(){ const currentTime = (audio.duration * songRange.value) / 100; audio.currentTime = currentTime; } function loadedmetadata() { const totalDuration = audio.duration; totalRange.textContent = formatTime(totalDuration); songRange.max = totalDuration; }; setInterval(function() { changeColors(); }, 3000); audio.addEventListener("ended", playNextSong); audio.addEventListener('loadedmetadata', loadedmetadata); playBtn.addEventListener("click", playPause); nextBtn.addEventListener("click", playNextSong); prevBtn.addEventListener("click", playPrevSong); volumeBtn.addEventListener("input", volumeControl); audio.addEventListener("timeupdate", songProgressbar); songRange.addEventListener("input", songRangeUpdate); updatePlaylistUI(); loadSong(currentSongIndex); </script> </body> </html>