Implementing a web player with JavaScript

Implementing a web player with JavaScript

Today I will share with you how to write a player on a web page using JavaScript.

Everyone is familiar with the player, so how can we realize it?

Below is a picture of a player I made

First, let's look at this player from top to bottom. At the top is the title (head): My Music; in the middle is the content (body): songs; at the bottom (foot): controls for controlling music playback. The title part only has the title: My Music, and the middle content part is the playlist. Each song has a play icon (only available when music is playing) and song information. The bottom part has some icons for controlling playback, the name of the currently playing song, the song playback progress, and the song playback time.

For layout, we need to keep the structure and style separate, with the structure written in HTML and the style written in CSS.

Web page structure layout: My songs are not written directly, but loaded as json objects. So the content part of the song I wrote here is just a format. I wrote the icons for the previous song/play, pause/next song using the a tag, and added the icons to the a tag background. I use two divs to implement the song playback progress. The inner div displays gray as the total progress, and the upper div displays white as the current song playback progress.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./css/yinyue.css" >
</head>
<body>
<!--The entire player part-->
<div class="music-list">
    <!--Title section-->
    <div class="head">My Music</div>
    <!--Content section-->
    <div class="body" id="tbody">
        <!--Format of each song-->
        <div class="item">
            <!--Small icon when the song is playing-->
            <div class="item-logo box11"><img src="imgs/playing.gif"></div>
            <!--Song Information-->
            <div class="item-name">Palm——Ding Dang</div>
        </div>
    </div>
    <!--Bottom part-->
    <div class="foot">
        <!-- Previous/Play, Pause/Next icon -->
        <div class="box1">
            <!-- Previous song icon -->
            <a href="javascript:;" class="btn-pre"></a>
            <!--Play, pause icon-->
            <a href="javascript:;" class="btn-play" id="btnPlay"></a>
            <!--Next song icon-->
            <a href="javascript:;" class="btn-next"></a>
        </div>
        <!--Current time of song playing-->
        <div class="box2 play-current">0.00</div>
        <!--Song playback progress and song name-->
        <div class="box3 mid">
            <!--Song Title-->
            <span id="playingNmae" class="m-name">My Music</span>
            <!--Song playback progress-->
            <div class="box31"></div>
            <div class="box32"><a href="" class=" rel="external nofollow" dot"></a></div>
        </div>
        <!--Total time of song playing-->
        <div class="box4 play-duration">4.13</div>
    </div>
</div>
<script src="js/data.js"></script>
<script src="js/index.js"></script>
</body>
</html>

Web page style layout: You can set good-looking fonts and color styles by yourself. In addition, when setting background: url("../imgs/play-default.png") no-repeat;, please note that the path in the url should have two dots to indicate exiting the current directory and going to the root directory. Also set the background to no-repeat (non-tiling). When using absolute positioning, you must follow the child-parent principle and pay attention to setting the z-index attribute.

/*Remove the inner and outer margins of the label*/
* {
    margin: 0;
    padding: 0;
}
/*Set the entire player style:
The layout is flexbox,
Horizontally centered,
width and height,
With border,
Set the elastic direction of the elastic box: column (vertical)
*/
.music-list {
    display: flex;
    margin: 0 auto;
    height: 600px;
    width: 400px;
    border: 1px solid #ccc;
    flex-direction: column;
}
/*Set the title section*/
.head{
    flex: 1;
    background: #3498db;
    color: #fff;
    font: 24px "Chinese Xingkai";
    display: flex;
    /*Horizontal axis centered*/
    justify-content: center;
    /*Center the vertical axis*/
    align-items: center;
    border-bottom: 1px solid white;
    box-sizing: border-box;
}
/*Set the content part*/
.body {
    flex: 7;
    /*Hide the excess part*/
    overflow-x:hidden;
}
/*Set the bottom section*/
.foot {
    flex: 2;
    display: flex;
    background: #3498db;
    color: #fff;
    font-size: 14px;
    border-top: 1px solid white;
    box-sizing: border-box;
}
/*Set the format of each song*/
.item {
    display: flex;
    height: 50px;
    line-height: 50px;
    background: #3498db;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
    transition: all .5s;
}
/*Except the last song, all other songs will display the bottom border*/
.item:not(:last-child) {
    border-bottom: 1px solid white;
}
/*Set the background color of the small icon when the song is playing*/
.box11 {
    background: #f0f0f0;
}
/*Set song information*/
.item-name {
    flex: 6;
    /*Don't write next to the border*/
    padding: 0 10px;
}
/*Mouse hover effect*/
.item:hover {
    background: #2980b9;
}
/*The effect of mouse click*/
.item:active {
    /*If you want a 3D effect for the click event, you can add a box shadow and relative positioning*/
    position: relative;
    top: 2px;
    left: 2px;
    box-shadow: 5px 5px 10px rgba(0, 0, 0, .5);
}
/*Set the size of the icons for previous/play, pause/next song*/
.box1 {
    flex: 3;
    display: inline-block;
}
/*Set the size of the current time of the song playing*/
.box2 {
    flex: 1;
    display: inline-block;
    padding: 50px 0;
    text-align: left;
}
/*Set the progress of song playback and the size of the song name*/
.box3 {
    flex: 5;
    display: inline-block;
    position: relative;
    padding: 35px 0;
}
/*Set the total time occupied by the song playback*/
.box4 {
    flex: 1;
    display: inline-block;
    padding: 50px 0;
    text-align: right;
}
/*Assign the icon size for previous/play, pause/next song*/
.box1 a {
    display: inline-block;
    margin: 50px 0;
    width: 30%;
    height: 50%;
}
/*Set the previous song icon*/
.btn-pre {
    background: url("../imgs/pre-default.png") no-repeat;
    cursor: pointer;
}
/*Set the mouse hover effect of the previous song icon*/
.btn-pre:hover {
    background: url("../imgs/pre-active.png") no-repeat;
}
/*Set the playback icon*/
.btn-play {
    background: url("../imgs/play-default.png") no-repeat;
    cursor: pointer;
}
/*Set the mouse hover effect of the play icon*/
.btn-play:hover {
    background: url("../imgs/play-active.png") no-repeat;
}
/*Set the pause icon*/
.btn-pause {
    background: url("../imgs/pause-default.png") no-repeat;
    cursor: pointer;
}
/*Set the pause icon mouse hover effect*/
.btn-pause:hover {
    background: url("../imgs/pause-active.png") no-repeat;
}
/*Set the icon for the next song*/
.btn-next {
    background: url("../imgs/next-default.png") no-repeat;
    cursor: pointer;
}
/*Set the mouse hover effect of the next song icon*/
.btn-next:hover {
    background: url("../imgs/next-active.png") no-repeat;
}
/*Set the font of the song title*/
.m-name {
    font: 20px "KaiTi";
}
/*Set the total progress of song playback*/
.box31 {
    position: absolute;
    width: 100%;
    height: 2px;
    background: #cacaca;
    z-index: 1;
}
/*Set the current progress of the song*/
.box32 {
    position: absolute;
    width: 20%;
    height: 2px;
    background: white;
    z-index: 2;
}
/*The small dot moves along with the current progress of the song*/
.dot {
    position: absolute;
    display: inline-block;
    right: 0;
    top: -2px;
    height: 5px;
    width: 5px;
    border-radius: 2.5px;
    background: #fff;
}

JavaScript code: Because the play icon and the pause icon change alternately when clicked, and these icons are displayed as the background, we can just change the background of the a tag, that is, change the background when clicked (the way to change the background is to change a class). When setting the progress of song playback, you can look at some events in audio, such as loadeddata, timeupdate, and ended. Ended can be used to achieve the function of automatically playing the next song. When setting the forward and backward functions, pay attention to obtaining the position of the mouse click (that is, the distance from the starting point). The song progress can be changed by setting a value to player.currentTime.

// Create a player DOM object var player = document.createElement('audio');
//Set a value to save the index of the currently playing song var currentIndex = 0;
//Set a flag to determine whether the song is playing var isPlay = false;
​
//Dynamically load songs (function () {
    //Set a value to save all songs DOM object var html = '';
    //Get the DOM objects of all songs for (var i = 0; i < musics.length; i++) {
        var m = musics[i];
        //Set the format of each song html += `<div class="item" data-index="${i}">
                      <div class="item-logo box11"></div>
                      <div class="item-name">${m.name}---${m.artist}</div>
                 </div>`
    }
    //Add all songs document.getElementById('tbody').innerHTML = html;
    //Give the player a default playback address player.src = musics[currentIndex].path;
})();
​
//Set click event for each song var trs = document.querySelectorAll('.item')
for (let i = 0; i < trs.length; i++) {
    trs[i].addEventListener('click', function () {
        //Clear the playback status of the previous song clearStatus();
        //Get the song index var index = this.dataset.index;
        currentIndex = index;
        var msc = musics[index];
        //Set the playback address for the player player.src = msc.path;
        //Start playing startPlayer();
    })
}
//Function: start playing function startPlayer() {
    //Set the play flag isPlay = true;
    // Play the song player.play();
    trs[currentIndex].style.background = '#2980b9';
    // Add a small icon for playing songs trs[currentIndex].querySelector('.item-logo').innerHTML = '<img src="imgs/playing.gif">';
    //Set the icon to play status document.querySelector('#btnPlay').className = 'btn-pause';
    //Set the song name document.querySelector('#playingNmae').innerText = `${musics[currentIndex].name} - ${musics[currentIndex].artist}`;
}
//Function: Clear the playback status of the previous song function clearStatus() {
    trs[currentIndex].style.background = '';
    trs[currentIndex].querySelector('.item-logo').innerHTML = '';
}
//Function: Pause playback function pausePlay() {
    //Pause playbackplayer.pause();
    //Set the play flag isPlay = false;
    //Set the icon to pause state document.getElementById('btnPlay').className = 'btn-play';
}
//Function: Implement the click event of the previous song function document.querySelector('.btn-pre').addEventListener('click', function () {
    //Pause playback pausePlay();
    //Clear the playback status of the previous song clearStatus();
    //Realize the previous song function if (currentIndex == 0) {
        currentIndex = musics.length - 1;
    } else {
        --currentIndex;
    }
    console.log(currentIndex)
    //Set the playback address for the player player.src = musics[currentIndex].path;
    startPlayer();
​
})
//Function: Implement the click event of the song play function document.getElementById('btnPlay').addEventListener('click', function () {
    //By judging the play flag if (isPlay) {
        pausePlay();
    } else {
        startPlayer();
    }
})
//Function: Implement the click event of the next song function document.querySelector('.btn-next').addEventListener('click', function () {
    pausePlay();
    clearStatus();
    if (currentIndex == musics.length - 1) {
        currentIndex = 0;
    } else {
        ++currentIndex;
    }
    console.log(currentIndex)
    player.src = musics[currentIndex].path;
    startPlayer();
​
})
//Set the song playing progress var now = 0;
var total = 0;
//Event after song data is loaded player.addEventListener('loadeddata', function () {
    // The current progress of the song (time)
    now = player.currentTime;
    // The total progress of the song (time)
    total = player.duration;
    //Display the song progress (time) on the player document.querySelector('.play-current').innerText = fmtTime(now);
    document.querySelector('.play-duration').innerText = fmtTime(total);
})
//When currentTime (the current progress time of the song) is updated, the timeupdate event will be triggered player.addEventListener('timeupdate', function () {
    //Get the current progress (time) of the song
    now = player.currentTime;
    // Current progress of the song var p = now / total * 100 + '%';
    //Synchronize the current progress of the song to the progress bar document.querySelector('.box32').style.width = p;
    document.querySelector('.play-current').innerText = fmtTime(now);
})
//Song end event (function of automatically playing the next song)
player.addEventListener('ended', function () {
    //Clear the playback status of the previous song clearStatus();
    //Play the next songcurrentIndex++;
    if (currentIndex >= musics.length) {
        currentIndex = 0;
    }
    player.src = musics[currentIndex].path;
    startPlayer();
})
//Forward song event document.querySelector('.box31').addEventListener('click', function (e) {
    //Get the position of the mouse click let right = e.offsetX;
    // Set the progress bar to the position where the mouse is clicked document.querySelector('.box32').style.width = right;
    //Calculate the progress of the song at the mouse click position let seekTo = right/200*total;
    //Set the progress of the song player.currentTime=seekTo;
        })
//Back song event document.querySelector('.box32').addEventListener('click', function (e) {
    let left = e.offsetX;
    document.querySelector('.box32').style.width = left;
    let seekTo = left/200*total;
    player.currentTime=seekTo;
})
//Function: format time function fmtTime(time) {
    time *= 1000;
    time = new Date(time);
    var m = time.getMinutes();
    var s = time.getSeconds();
    m = m < 10 ? '0' + m : m;
    s = s < 10 ? '0' + s : s;
    return m + ':' + s;
}

musics:

var musics = [
    {
        artist: "GALA",
        id: 1,
        name: "Chasing Dreams with a Pure Heart",
        path: "musics/1.mp3"
    },
    {
        artist: "Chopstick Brothers",
        id: 2,
        name: "Father",
        path: "musics/2.mp3"
    },
    {
        artist: "丁当",
        id: 3,
        name: "Palm",
        path: "musics/3.mp3"
    },
    {
        artist: "Sasaki Lizi",
        id: 4,
        name: "Good Night",
        path: "musics/4.mp3"
    },
    {
        artist: "Angela Zhang",
        id: 5,
        name: "Invisible Wings",
        path: "musics/5.mp3",
    },
    {
        artist: "Rainie Yang",
        id: 6,
        name: "Rain Love",
        path: "musics/6.mp3",
    },
    {
        artist: "Yao Band",
        id: 7,
        name: "Meteor",
        path: "musics/7.mp3",
    },
    {
        artist: "Escape Plan",
        id: 8,
        name: "Fly Again (MV Version)",
        path: "musics/8.mp3",
    },
    {
        artist: "Jin Guisheng",
        id: 9,
        name: "Between Rainbows",
        path: "musics/9.mp3",
    }
]

After you have learned jQuery and some frameworks, some of the above things can be written using jQuery and frameworks, which is more convenient.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • (jsp/html) Embedding a player on a web page (common player code compilation)
  • Use js to teach you how to easily create an HTML music player
  • Universal flv web player code implemented by js
  • JavaScript to implement a simple HTML5 video player
  • javascript player control
  • js implements a music player compatible with IE, FF, Chrome, Opera and Safari
  • JavaScript to achieve music player with playlist example sharing
  • Detailed explanation of how to use the Js video player plug-in Video.js
  • A cool picture player js focus effect code
  • JS+html5 to create a simple music player

<<:  Detailed explanation of MySQL Innodb storage structure and storage of Null values

>>:  Detailed tutorial on deploying Jenkins based on docker

Recommend

Detailed tutorial on Docker pulling Oracle 11g image configuration

Without further ado Start recording docker pullin...

How to enable TLS and CA authentication in Docker

Table of contents 1. Generate a certificate 2. En...

Solution to Docker pull timeout

Recently, Docker image pull is very unstable. It ...

The actual process of encapsulating axios in the project

Table of contents Preface Benefits of axios encap...

Analysis of MySQL concurrency issues and solutions

Table of contents 1. Background 2. Slow query cau...

Delegating Privileges in Linux Using Sudo

Introduction to sudo authority delegation su swit...

Detailed explanation of the order of JS object traversal

Some of you may have heard that the order of trav...

How does Vue3's dynamic components work?

Table of contents 1. Component Registration 1.1 G...

ThingJS particle effects to achieve rain and snow effects with one click

Table of contents 1. Particle Effects 2. Load the...

How to use domestic image warehouse for Docker

1. Problem description Due to some reasons, the d...

About the problem of offline installation of Docker package on CentOS 8.4

The virtual machine used is CentOS 8.4, which sim...

Detailed analysis of the chmod command to modify file permissions under Linux

Use the Linux chmod command to control who can ac...

Element uses scripts to automatically build new components

Table of contents background How does element-ui&...

Example code for implementing WeChat account splitting with Nodejs

The company's business scenario requires the ...