search
HomeWeb Front-endH5 TutorialUsing HTML5 to implement web music player

This article mainly introduces the sample code of HTML5 web music player. The content is quite good. Now I will share it with you and give it as a reference.

This article introduces the sample code of HTML5 web music player and shares it with everyone. The details are as follows:

1 Function introduction

Introduced in HTML5 The audio and video tag allows us to play audio and video directly without using other plug-ins. Next we will use H5's audio tag and its related attributes and methods to create a simple music player. It mainly includes the following functions:

1. Play and pause, previous and next songs

2. Adjust volume and playback progress bar

3. Switch according to the list Current song

Let’s take a look at the final result:

The structure of this music player is mainly divided into three parts: song information, player and Playlist, let’s focus on the player part. First, put three audio tags in the player for playback:

<audio id="music1">浏览器不支持audio标签
<source  src="media/Beyond - 光辉岁月.mp3"></source>
</audio>
<audio id="music2">浏览器不支持audio标签
<source  src="media/Daniel Powter - Free Loop.mp3"></source>
</audio>
<audio id="music3">浏览器不支持audio标签
<source  src="media/周杰伦、费玉清 - 千里之外.mp3"></source>
</audio>

The following playlist also corresponds to the three audio tags:

<p id="playList">
    <ul>
        <li id="m0">Beyond-光辉岁月</li>
        <li id="m1">Daniel Powter-Free Loop</li>
        <li id="m2">周杰伦、费玉清-千里之外</li>
    </ul>
</p>

Next we start to gradually implement the above mentioned Function, let’s complete the play and pause functions first. When pressing the play button, we need to make the progress bar advance with the progress of the song, and the play time gradually increases. At the same time, the play button becomes a pause button, and the style of the play list also changes accordingly.

Before doing the function, we must first obtain the IDs of the three audio tags and store them in an array for subsequent use.

var music1= document.getElementById("music1");
var music2= document.getElementById("music2");
var music3= document.getElementById("music3");
var mList = [music1,music2,music3];

2 Play and pause:

We can now complete the function of the play button. First, set a flag to mark the playback status of the music, and then Set a default value for the index index of the array:

Then judge the playback status, call the corresponding function, and modify the value of the flag and the corresponding item style of the list:

function playMusic(){
if(flag&&mList[index].paused){
            mList[index].play();
        document.getElementById("m"+index).style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
progressBar();
        playTimes();
        play.style.backgroundImage = "url(media/pause.png)";
        flag = false;
}else{
        mList[index].pause();
        flag = true;
        play.style.backgroundImage = "url(media/play.png)";
}
}

Called in the above code There are multiple functions, among which play and pause are the methods that come with the audio tag, while other functions are defined by ourselves. Let's take a look at how these functions are implemented and what functions they correspond to.

3 Progress bar and playback time:

The first is the progress bar function, which obtains the entire duration of the song, and then compares the current playback progress with the total length of the progress bar. Multiply to calculate the position of the progress bar.

function progressBar(){
var lenth=mList[index].duration;
timer1=setInterval(function(){
        cur=mList[index].currentTime;//获取当前的播放时间
        progress.style.width=""+parseFloat(cur/lenth)*300+"px";
        progressBtn.style.left= 60+parseFloat(cur/lenth)*300+"px";
},10)
}

The following is the function of changing the playback time. Here we set up a timing function and execute it every once in a while to change the playback time. Because the song duration we obtained is calculated in seconds, we need to use the if statement to convert the duration judgment and change the playback time to display in minutes and seconds.

function playTimes(){
timer2=setInterval(function(){
        cur=parseInt(mList[index].currentTime);//秒数
        var minute=parseInt(cur/60);
        if (minute<10) {
            if(cur%60<10){
                playTime.innerHTML="0"+minute+":0"+cur%60+"";
            }else{
                playTime.innerHTML="0"+minute+":"+cur%60+"";
            }
        } else{
            if(cur%60<10){
                playTime.innerText= minute+":0"+cur%60+"";
            }else{
                playTime.innerText= minute+":"+cur%60+"";
            } 
        } 
},1000);
}

4 Adjust the playback progress and volume:

Next we will complete the functions of adjusting the playback progress and adjusting the volume through the progress bar.

The function of adjusting the playback progress is implemented by using the event object. Because the offsetX attribute is only available in IE events, it is recommended to use IE browser to view the effect. First add an event listener to the progress bar. When the mouse is clicked on the progress bar, the mouse position is obtained, and the current playback progress is calculated based on the position divided by the total length of the progress bar, and then the song is set.

//调整播放进度
total.addEventListener("click",function(event){
var e = event || window.event;
document.onmousedown = function(event){
        var e = event || window.event;
        var mousePos1 = e.offsetX;
        var maxValue1 = total.scrollWidth;
        mList[index].currentTime = (mousePos1/300)*mList[index].duration;
        progress.style.width = mousePos1+"px";
        progressBtn.style.left = 60+ mousePos1 +"px";
}
})

The following is the volume adjustment function. We use dragging to adjust the volume. The idea is to add event monitoring to the button ball of the volume bar, and then calculate the button ball relative to the volume bar based on the dragged position. The overall position, and finally the current volume is obtained by multiplying the calculation result with the volume:

volBtn.addEventListener("mousedown",function(event){
var e = event || window.event;
var that =this;
//阻止球的默认拖拽事件
e.preventDefault();
document.onmousemove = function(event){
var e = event || window.event;
var mousePos2 = e.offsetY;
var maxValue2 = vol.scrollHeight;
if(mousePos2<0){
            mousePos2 = 0;
}
if(mousePos2>maxValue2){
            mousePos2=maxValue2;
}
mList[index].volume = (1-mousePos2/maxValue2);
console.log(mList[index].volume);
volBtn.style.top = (mousePos2)+"px";
volBar.style.height = 60-(mousePos2)+"px";
document.onmouseup = function(event){
            document.onmousemove = null;
            document.onmouseup = null;
}
}
})

5 Song switching

Finally, we will implement the more complex song switching function.

Let’s first look at using the previous and next buttons to switch. There are several issues we should pay attention to when switching music: First, we need to stop the currently playing music and switch to the next one. A piece of music; secondly, the progress bar and playback time must be cleared and recalculated; thirdly, the song information must be changed accordingly, and the playlist style under the player must also change. After figuring out the above three points, we can start to implement the function.

//上一曲
function prevM(){
clearInterval(timer1);
clearInterval(timer2);
stopM();
qingkong();
cleanProgress();
--index;
if(index==-1){
        index=mList.length-1;
}
clearListBgc();
document.getElementById("m"+index).style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
changeInfo(index);
mList[index].play();
progressBar();
playTimes();
if (mList[index].paused) {
    play.style.backgroundImage = "url(media/play.png)";
}else{
    play.style.backgroundImage = "url(media/pause.png)";
}
} 
//下一曲
function nextM(){
clearInterval(timer1);
clearInterval(timer2);
stopM();
qingkong();
cleanProgress();
++index;
if(index==mList.length){
    index=0;
}
clearListBgc();
document.getElementById("m"+index).style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
changeInfo(index);
mList[index].play();
progressBar();
playTimes();
if (mList[index].paused) {
    play.style.backgroundImage = "url(media/play.png)";
}else{
    play.style.backgroundImage = "url(media/pause.png)";
}
}

The code below is to click on the list to switch songs.

m0.onclick = function (){
clearInterval(timer1);
clearInterval(timer2);
qingkong();
flag = false;
stopM();
index = 0;
pauseall();
play.style.backgroundImage = "url(media/pause.png)";
clearListBgc();
document.getElementById("m0").style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
mList[index].play();
cleanProgress();
progressBar();
changeInfo(index);
playTimes();
}
m1.onclick = function (){
clearInterval(timer1);
clearInterval(timer2);
flag = false;
qingkong();
stopM();
index = 1;
pauseall();
clearListBgc();
play.style.backgroundImage = "url(media/pause.png)";
document.getElementById("m1").style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
mList[index].play();
cleanProgress();
changeInfo(index);
progressBar();
playTimes();
}
m2.onclick = function (){
clearInterval(timer1);
clearInterval(timer2);
flag = false;
qingkong();
stopM();
index = 2;
pauseall();
play.style.backgroundImage = "url(media/pause.png)";
clearListBgc();
document.getElementById("m2").style.backgroundColor = "#A71307";
document.getElementById("m"+index).style.color = "white";
mList[index].play();
cleanProgress();
changeInfo(index);
progressBar();
playTimes();
}

The idea of ​​switching songs through playlists is similar to switching through buttons. It just sets which song should be played currently according to the corresponding list item.

Several methods are called in the function of switching songs above. Let’s take a look at the uses of these methods.

First switch the song information:

function changeInfo(index){
if (index==0) {
    musicName.innerHTML = "光辉岁月";
    singer.innerHTML = "Beyond";
}
if (index==1) {
    musicName.innerHTML = "Free Loop";
    singer.innerHTML = "Daniel Powter";
}
if (index==2) {
    musicName.innerHTML = "千里之外";
    singer.innerHTML = "周杰伦、费玉清";
}
}

Then clear the two timers:

//将进度条置0
function cleanProgress(timer1){
if(timer1!=undefined){
    clearInterval(timer1);
}
progress.style.width="0";
progressBtn.style.left="60px";
} 
function qingkong(timer2){ 
if(timer2!=undefined){
    clearInterval(timer2);
}
}

Then stop the playing music and restore the playing time.

function stopM(){
if(mList[index].played){
    mList[index].pause();
    mList[index].currentTime=0;
    flag=false;
}
}

Finally, change the style of the playlist below:

function clearListBgc(){
document.getElementById("m0").style.backgroundColor = "#E5E5E5";
document.getElementById("m1").style.backgroundColor = "#E5E5E5";
document.getElementById("m2").style.backgroundColor = "#E5E5E5";
document.getElementById("m0").style.color = "black";
document.getElementById("m1").style.color = "black";
document.getElementById("m2").style.color = "black";
}

At this point, we have basically completed the music player. Let’s take a look at the effect of the animation:

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

related suggestion:

Solution to the problem that the video tag in html5 cannot play mp4

About the control analysis of the new H5 attributes audio audio and video video

The above is the detailed content of Using HTML5 to implement web music player. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools