The Simple Music Player - Upload Cable
Equally streaming is increasingly beingness adopted past users, online media players have go essential for consuming media on the internet. Music players permit 1 to relish music in any browser and supports a lot of the features of an offline music thespian.
Nosotros volition be creating a music player with a clean user interface that can be used to play music in the browser. We volition also implement features like seeking and volume control. HTML has several methods in the HTMLMediaElement interface that can be used to play sound files and command its playback without using any other library.
We volition start by creating the HTML layout first that defines the construction of the player, brand information technology look expert by styling using CSS and and so write the player logic for all the functions in JavaScript.
The HTML Layout
The HTML layout defines the element structure that would exist shown on the page. The player can be divided into the following portions:
- Details Portion: This section shows the details of the electric current track existence played. It includes the track number, track album, runway proper name and track artist.
- Buttons Portion: This section shows the buttons that are used to control the playback of the track. It includes the play/pause push button, the previous and next track buttons. They would have an onclick() method that calls a specific function defined in the JavaScript file.
- Sliders Portion: This section contains the seek slider and volume slider that can be used to command the playback and volume.
We will be using FontAwesome icons to get the icons for all the buttons used on the page. The custom CSS and JavaScript we will write later is also linked in the file.
The HTML lawmaking is every bit follows:
html
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >Simple Music Player</ championship >
< link rel = "stylesheet"
href =
< link rel = "stylesheet" blazon = "text/css" href = "style.css" >
</ head >
< body >
< div grade = "player" >
< div class = "details" >
< div class = "now-playing" >PLAYING x OF y</ div >
< div class = "track-art" ></ div >
< div class = "runway-proper name" >Track Name</ div >
< div class = "track-artist" >Runway Artist</ div >
</ div >
< div class = "buttons" >
< div class = "prev-rail" onclick = "prevTrack()" >
< i form = "fa fa-stride-backward fa-2x" ></ i >
</ div >
< div form = "playpause-track" onclick = "playpauseTrack()" >
< i class = "fa fa-play-circumvolve fa-5x" ></ i >
</ div >
< div class = "adjacent-track" onclick = "nextTrack()" >
< i class = "fa fa-pace-forrard fa-2x" ></ i >
</ div >
</ div >
< div class = "slider_container" >
< div class = "electric current-fourth dimension" >00:00</ div >
< input blazon = "range" min = "1" max = "100"
value = "0" class = "seek_slider" onchange = "seekTo()" >
< div course = "full-duration" >00:00</ div >
</ div >
< div form = "slider_container" >
< i form = "fa fa-book-down" ></ i >
< input blazon = "range" min = "ane" max = "100"
value = "99" class = "volume_slider" onchange = "setVolume()" >
< i course = "fa fa-volume-up" ></ i >
</ div >
</ div >
< script src = "main.js" ></ script >
</ body >
</ html >
The CSS Styling
Using CSS nosotros can manner the unlike portions to make it more visually appealing:
- The flex layout is used to conform the diverse elements of the player and marshal them to the centre of the folio.
- The track art prototype is given a fixed dimension and made rounded using the border-radius property.
- The two sliders have been modified from their default look by using the advent property. The elevation and background are changed to suit the colour scheme. They are also given slight transparency that smoothly transitions to the full opacity using the transition property.
- All the playback controls have their cursor holding set so that it changes to a pointer whenever the mouse hovers over information technology.
css
body {
background-colour : lightgreen;
transition: background-color . 5 due south;
}
.thespian {
height : 95 vh;
brandish : flex;
align-items: center ;
flex- direction : column;
justify- content : middle ;
}
.details {
brandish : flex;
align-items: center ;
flex- direction : cavalcade;
justify- content : center ;
margin-superlative : 25px ;
}
.track-art {
margin : 25px ;
top : 250px ;
width : 250px ;
groundwork-image : URL(
background- size : cover;
background-position : center ;
border-radius: 15% ;
}
.now-playing {
font-size : 1 rem;
}
.track-proper noun {
font-size : 3 rem;
}
.track-creative person {
font-size : 1.5 rem;
}
.buttons {
display : flex;
flex- direction : row;
align-items: center ;
}
.playpause-track,
.prev-rail,
.adjacent-rail {
padding : 25px ;
opacity: 0.8 ;
transition: opacity . 2 s;
}
.playpause-runway:hover,
.prev-runway:hover,
.next-rail:hover {
opacity: i.0 ;
}
.slider_container {
width : 75% ;
max-width : 400px ;
brandish : flex;
justify- content : middle ;
align-items: center ;
}
.seek_slider, .volume_slider {
-webkit-appearance: none ;
-moz-advent: none ;
advent: none ;
elevation : 5px ;
background : black ;
opacity: 0.7 ;
-webkit-transition: . 2 s;
transition: opacity . 2 s;
}
.seek_slider::-webkit-slider-thumb,
.volume_slider::-webkit-slider-thumb {
-webkit-appearance: none ;
-moz-appearance: none ;
appearance: none ;
width : 15px ;
meridian : 15px ;
groundwork : white ;
cursor : pointer ;
edge-radius: 50% ;
}
.seek_slider:hover,
.volume_slider:hover {
opacity: one.0 ;
}
.seek_slider {
width : 60% ;
}
.volume_slider {
width : 30% ;
}
.current-time,
.total-duration {
padding : 10px ;
}
i.fa-volume-down,
i.fa-volume-up {
padding : 10px ;
}
i.fa-play- circle ,
i.fa-pause- circle ,
i.fa-footstep-forward,
i.fa-step-backward {
cursor : pointer ;
}
The event of the HTML layout and CSS styling would give the following appearance:
JavaScript logic of the histrion:
The logic of the histrion is defined in the JavaScript file. There are several functions that work together to handle all the functions of the player.
Step ane: Defining all the variables and accessing the HTML elements
The required elements in the HTML layout that are to be dynamically changed are commencement selected using the querySelector() method. They are so assigned variable names then that they could be accessed and modified. Other variables that would be accessed throughout the program are also defined.
javascript
permit now_playing = document.querySelector( ".now-playing" );
let track_art = document.querySelector( ".track-art" );
let track_name = document.querySelector( ".track-name" );
let track_artist = certificate.querySelector( ".runway-artist" );
let playpause_btn = document.querySelector( ".playpause-track" );
let next_btn = document.querySelector( ".next-track" );
let prev_btn = document.querySelector( ".prev-rails" );
let seek_slider = certificate.querySelector( ".seek_slider" );
permit volume_slider = certificate.querySelector( ".volume_slider" );
permit curr_time = certificate.querySelector( ".current-time" );
allow total_duration = document.querySelector( ".total-elapsing" );
let track_index = 0;
let isPlaying = false ;
let updateTimer;
let curr_track = document.createElement( 'sound' );
let track_list = [
{
name: "Dark Owl" ,
artist: "Broke For Costless" ,
image: "Image URL" ,
path: "Night_Owl.mp3"
},
{
name: "Enthusiast" ,
creative person: "Tours" ,
image: "Image URL" ,
path: "Enthusiast.mp3"
},
{
name: "Shipping Lanes" ,
artist: "Chad Hunker" ,
image: "Prototype URL" ,
path: "Shipping_Lanes.mp3" ,
},
];
Pace ii: Loading a new track from the tracklist
All the tracks that take to exist played are defined in the tracklist as objects. These objects contain backdrop like the proper name, artist, prototype and path to the track. Each of the tracks can so exist accessed using its track index.
To load a track, a office loadTrack() is defined which handles the post-obit things:
- Reset all the values of the previous rail
A resetValues() function is created which handles the resetting of the elapsing value and the slider to their initial values earlier a new runway starts. This prevents the jumping of the seek slider while the new track loads. - Loading the track
The audio element is assigned a new source using its src property. Information technology may exist given any path from the filesystem or a URL. The load() method is and then used on the audio chemical element to become the track prepare. - Updating the track fine art to be shown
The track fine art is fetched from the assortment and assigned with the assistance of the backgroundImage property. - Updating the track details to be shown
The runway details are fetched from the array and assigned with the help of the textContent property. - Adding event listeners to the rail
The media element has two event listeners added to information technology, the get-go one to update the current seek position and the second one to load the next track when the current track finishes. - Setting a random colored background
A coloured background is generated by randomising the carmine, dark-green and bluish values used and setting it as a color. The consequence is animated by using the transition property on the background-colour.
javascript
part loadTrack(track_index) {
clearInterval(updateTimer);
resetValues();
curr_track.src = track_list[track_index].path;
curr_track.load();
track_art.mode.backgroundImage =
"url(" + track_list[track_index].prototype + ")" ;
track_name.textContent = track_list[track_index].name;
track_artist.textContent = track_list[track_index].creative person;
now_playing.textContent =
"PLAYING " + (track_index + 1) + " OF " + track_list.length;
updateTimer = setInterval(seekUpdate, yard);
curr_track.addEventListener( "concluded" , nextTrack);
random_bg_color();
}
function random_bg_color() {
let red = Math.floor(Math.random() * 256) + 64;
let green = Math.flooring(Math.random() * 256) + 64;
let blue = Math.flooring(Math.random() * 256) + 64;
let bgColor = "rgb(" + red + ", " + green + ", " + blue + ")" ;
document.body.manner.background = bgColor;
}
office resetValues() {
curr_time.textContent = "00:00" ;
total_duration.textContent = "00:00" ;
seek_slider.value = 0;
}
Pace three: Configuring the player buttons
A function playTrack() handles the playing of the currently loaded rails. The play() method of the HTMLMediaElement API is used for this role. The icon of the button too changes to the pause icon. This is washed by using one of the icons from the FontAwesome library and inserting it using innerHTML.
A function pauseTrack() handles the playing of the currently loaded rail. The intermission() method of the HTMLMediaElement API is used for this function. The icon of the button also changes back to the play icon. This is washed past using one of the icons from the FontAwesome library and inserting it using innerHTML.
These two functions are invoked depending on whether the rails is currently playing or non. The playpause() office handles the actual play/intermission command of the track.
A part prevTrack() handles the loading of the previous track and moving the index backward. The index is reset to the last track when the alphabetize reaches the kickoff runway. The loadTrack() method defined above is used for loading the new track.
Similarly, a role nextTrack() handles the loading of the side by side track and moving the index frontwards. The index is reset to the showtime track when the alphabetize reaches the last track. The loadTrack() method divers above is used for loading the new track.
javascript
function playpauseTrack() {
if (!isPlaying) playTrack();
else pauseTrack();
}
part playTrack() {
curr_track.play();
isPlaying = truthful ;
playpause_btn.innerHTML = '<i grade="fa fa-suspension-circle fa-5x"></i>' ;
}
function pauseTrack() {
curr_track.intermission();
isPlaying = imitation ;
playpause_btn.innerHTML = '<i class="fa fa-play-circle fa-5x"></i>' ;
}
office nextTrack() {
if (track_index < track_list.length - 1)
track_index += ane;
else track_index = 0;
loadTrack(track_index);
playTrack();
}
function prevTrack() {
if (track_index > 0)
track_index -= ane;
else track_index = track_list.length - i;
loadTrack(track_index);
playTrack();
}
Step 4: Configuring the sliders portion
Nosotros will be setting upwards two sliders that control the seek slider and the volume slider.
- The seek slider
The seek slider shows the electric current playback position on a slider by updating it with the current time of the track. A new function is created seekUpdate() which handles the updating of the seek slider relative to the current time of the track. The seek slider position is calculated and prepare using the value belongings.
Now, this role has to be chosen every time the track progresses farther. This tin can be done by scheduling it to be updated every second. This tin can be done using the setInterval() method with an interval of g milliseconds. This timer is cleared every time a new runway is loaded.
This role likewise handles the irresolute of the fourth dimension elapsed and the total duration of the runway, which is updated every fourth dimension this function fires. The minutes and the seconds are separately calculated and properly formatted to be displayed. - The volume slider
The book slider is used to display an fix the current volume of the track. A new role is created setVolume() which handles the setting of the volume slider whenever the user changes it.
javascript
function seekTo() {
seekto = curr_track.duration * (seek_slider.value / 100);
curr_track.currentTime = seekto;
}
role setVolume() {
curr_track.volume = volume_slider.value / 100;
}
function seekUpdate() {
allow seekPosition = 0;
if (!isNaN(curr_track.duration)) {
seekPosition = curr_track.currentTime * (100 / curr_track.duration);
seek_slider.value = seekPosition;
let currentMinutes = Math.flooring(curr_track.currentTime / threescore);
let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60);
let durationMinutes = Math.floor(curr_track.elapsing / 60);
permit durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60);
if (currentSeconds < x) { currentSeconds = "0" + currentSeconds; }
if (durationSeconds < 10) { durationSeconds = "0" + durationSeconds; }
if (currentMinutes < 10) { currentMinutes = "0" + currentMinutes; }
if (durationMinutes < 10) { durationMinutes = "0" + durationMinutes; }
curr_time.textContent = currentMinutes + ":" + currentSeconds;
total_duration.textContent = durationMinutes + ":" + durationSeconds;
}
}
Stride five: Starting the thespian
The commencement track is loaded by calling the loadTrack() office. This will load the first track from the tracklist and update all the details of the runway. The user tin can then get-go playing the track using the play push. The previous and adjacent rail push would load the previous and next rails respectively and start playing them.
The adjacent track is automatically loaded when a track finishes playing. The user can seek to a position in the track using the seek slider. The volume can also exist adapted using the volume slider.
javascript
Final Demonstration
The role player is now ready to be used in whatever browser. New tracks can be added to the tracklist to play the music of your choice.
Try Online: https://ide.geeksforgeeks.org/tryit.php/T3gdWUn4aX
Source Code: https://github.com/sayantanm19/js-music-player
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You tin can learn HTML from the ground upwards by post-obit this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground upwards past following this CSS Tutorial and CSS Examples.
Source: https://www.geeksforgeeks.org/create-a-music-player-using-javascript/
Post a Comment for "The Simple Music Player - Upload Cable"