search
HomeWeb Front-endJS TutorialMake a music player with native JS

Make a music player with native JS

Apr 17, 2018 pm 02:26 PM
javascriptplayermusic

This time I will bring you native JS to make a music player. What are the precautions for making a music player using native JS. Here are practical cases. Let’s take a look. .

Previous words                                                      I've been reviewing JS recently, and I think music players are quite interesting. Today I'm going to write a small music player using our most native JS~

The main function:

​​ 1. Support loop and random play

2. Support image rotation during playback

​​ 3. Support clicking on the

progress bar

to adjust the playback position and volume ​​ 4. Display the music playback time

5. Supports switching songs: previous song, next song, click on the song title to switch songs; pause playback, etc.~

There are two ways to add music:

① You can use an audio tag, so that the address of the music should be stored in an array;

②The second way is to add a few audio tags if there are several songs, and then get all the background music (in the example, we first add three pieces of music and put them into an array. Of course, you can choose any song you like. ).

<audio>
   <source></source>
</audio>
<audio>
   <source></source>
</audio>
<audio>
   <source></source>
</audio>
rrree

1Click to play and pause

The first thing we should be clear about is that when clicking the button to play, the following should be implemented:

①The music starts playing;

②The progress bar starts to move forward as the song plays;

③The picture starts to rotate as the song plays;

④The playback time starts;

Correspondingly, when we click the play button again, we can make it pause:

①The song pauses;

② Let the progress bar pause at the same time;

③ Pause the playback time at the same time;

④The picture stops rotating;

Note: The above start and pause operations must be synchronized!

After clarifying our ideas, we can implement them one by one~

Click to play/pause

play1=document.getElementById("play1");
play2=document.getElementById("play2");
play3=document.getElementById("play3");
play=[play1,play2,play3];
Because play and pause are on the same button, the above methods will be called. Let’s take a detailed look at what functions each function implements:

Picture rotation

 //点击播放、暂停
  function start(){
   minute=0;
    if(flag){
      imagePause();
      play[index].pause();
     }else{
      rotate();
      play[index].play();
      reducejindutiao();
      addtime();
      jindutiao();
      for (var i=0;i<play.length></play.length>
The above is the function of image rotation. When the music is playing, calling the rotate() function can realize the rotation of the image!

Also clear the

timer

function. When the music is paused, imagePause() is called, and the image rotation timer is cleared:

//图片旋转,每30毫米旋转5度
  function rotate(){
    var deg=0;
    flag=1;
    timer=setInterval(function(){
    image.style.transform="rotate("+deg+"deg)";
      deg+=5;
       if(deg>360){
        deg=0;
        }
    },30);
 }
In this way, we have already implemented the function of image rotation~

progress bar

First define two p's with the same width, length, and different colors. Use the

current

time attribute to pass the current playback time. Set the initial length of a p to zero, and then use the current playback event to Adjusting the length of p can achieve the effect of a scroll bar.

function imagePause(){
    clearInterval(timer);
    flag=0;
 }
In this way, the progress bar is completed~

play time

The playback time of music is also changed at any time using currenttime, but it should be noted that the timing unit of currenttime is seconds.

function jindutiao(){
   //获取当前歌曲的歌长
   var lenth=play[index].duration;
    timer1=setInterval(function(){
    cur=play[index].currentTime;//获取当前的播放时间
     fillbar.style.width=""+parseFloat(cur/lenth)*300+"px";
      },50)
}

2 Cutting songs

I have done two ways to achieve cutting songs: ①Click the previous song and next song buttons to switch songs;

//播放时间
   function addtime(){
      timer2=setInterval(function(){
       cur=parseInt(play[index].currentTime);//秒数
        var temp=cur;
       minute=parseInt(temp/60);
       if(cur%60<p style="text-align: left;">
②Click on the song title to switch between songs; </p><pre class="brush:php;toolbar:false"> //上一曲
  function reduce(){
          qingkong();
          reducejindutiao();
          pauseall();
          index--;
          if(index==-1){
            index=play.length-1;
          }
          start();
        }
        //下一曲
        function add(){
          qingkong();
          reducejindutiao();
          pauseall();
          index++;
          if(index>play.length-1){
            index=0;
          }
          start();
        }

Note: Don’t forget our progress bar when switching songs!

Clear the timer for the progress bar scrolling, and then restore the length of p to 0;

 //点击文字切歌
        function change(e){
          var musicName=e.target;
          //先清空所有的
          for (var i=0;i<audioall.length><p style="text-align: left;">
At the same time the music stops: </p>
<pre class="brush:php;toolbar:false">//将进度条置0
 function reducejindutiao(){
     clearInterval(timer1);
      fillbar.style.width="0";
 }

Clear all timers:

 function qingkong(){//清空所有的计时器
    imagePause();
    clearInterval(timer2);
 }

3点击进度条调整播放进度及音量

首先应该理清一下逻辑:当点击进度条的时候,滚动条的宽度应该跟鼠标的offsetX一样长,然后根据进度条的长度来调整听该显示的时间。

(1) 给滚动条的p添加一个事件,当滚动条长度变化的时候歌曲的当前播放的时间调整,300是滚动条的总长度;

//调整播放进度
 function adjust(e){
   var bar=e.target;
   var x=e.offsetX;
   var lenth=play[index].duration;
   fillbar.style.width=x+"px";
   play[index].currentTime=""+parseInt(x*lenth/300)+"";
   play[index].play();
}

(2) 改变音量的滚动条,跟改变播放时间类似,利用volume属性(值为零到一);

 //调整音量大小
  function changeVolume(e){
    var x=e.offsetX+20;
    play[index].volume=parseFloat(x/200)*1;
    //改变按钮的位置
     volume3.style.left=""+x+"px";
}

4随机、循环播放

循环播放音乐的时候,直接index++当index的范围超过歌曲的长度的时候,index=0重新开始。随机播放的函数类似,当歌曲播放完毕的时候,随机产生一个0到play.length的数字就可以了。

 //随机播放歌曲
  function suiji(e){
          var img=e.target;
          img2.style.border="";
          img.style.border="1px solid red";
        }
        //顺序播放
        function shunxu(e){
          var img=e.target;
          img1.style.border="";
          img.style.border="1px solid red";
          clearInterval(suijiplay);
          shunxuplay=setInterval(function(){
            if(play[index].ended){
              add();
            }
          },1000);
        }

这样我们整个音乐播放器就完成了,大家可以自己写一个好看的界面,就更完美了

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue中computed属性的使用方法

ajax与跨域jsonp

用requireJS添加返回顶部功能

The above is the detailed content of Make a music player with native JS. 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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.