Fancy-Music-Player [Link]
A modern looking music player -- Built with HTML 5 Audio API
Tech Stack: HTML, CSS, Vanilla JS (No Framework!), HTML5 Audio API.
SEE On Youtube: https://www.youtube.com/watch?v=6LSp9cZDm6U&ab_channel=prasenjitsutradhar
*** IMPLEMENTATION ***
- Here we used html5 audio element without
controls
attributes, so that we can control things with javascript. - We have stored all image, song, artist in form of object and put them inside an array.
- On the page load, one song from the song array get selected and populated in the player with help of
loadSong
function. - When an user click on
play
icon, it'll first check whether a song is playing or not. To do that, there is a variableisPlaying
which is set tofalse
by default. - Now if a song is not playing, then the
playSong
function get executed which leads to changeisPlaying
totrue
and turnplay
icon intopause
icon and execute play method on audio element to start playing the song. - But if a song is playing, then the
pauseSong
function get executed which leads to changeisPlaying
tofalse
and turnpause
icon intoplay
icon and execute pause method on audio element to stop playing the song. - Next, on click of Previous Song, Next Song button, these two functions
prevSong
,nextSong
get executed accordingly, which basically increase / decrease the global variablesongIndex
& pass it toloadSong
function. Atlast, executeplaySong
function. - Next Task :-- Progress Bar, Current Time, Total duration .
- To get the current playback position, we listen for timeupdate event on the audio element.
- When this
event
get fired,updateProgressBar
function executes which do the heavy lifting task of all the maths & calculation of findingcurrentTime
,duration
from audio element and update the Progress Bar according as the current playback position changes. - Also, to update the current playback position on the click at different position on the Progress Bar,
setProgressBarByClick
function executes which findsclientWidth
,offsetX
on the Progress Bar element and evaluate the percentage ofoffsetX
inclientWidth
along Total Duration. - Then change
currentTime
property of audio element to triggertimeupdate
event which leads to change of all things like ProgressBar growth, current time, current playback position. - Final Task :-- switch to next song in line when current song runs out
- To do that, we listen for ended which fires when the current playlist is ended and execute
nextSong
function.