Home Web Front-end JS Tutorial Make a music player with native JS

Make a music player with native JS

Apr 17, 2018 pm 02:26 PM
javascript player music

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 id="play1">
   <source src="auto/旅行.mp3"></source>
</audio>
<audio id="play2">
   <source src="auto/薛明媛,朱贺 - 非酋.mp3"></source>
</audio>
<audio id="play3">
   <source src="auto/杨宗纬 - 越过山丘.mp3"></source>
</audio>
Copy after login
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];
Copy after login
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;i++) {
        audioall[i].style.color="white";
         }
      audioall[index].style.color="red";
     }
 }
Copy after login
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:

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.

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)
}
Copy after login

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<10){
       time.innerHTML=""+minute+":0"+cur%60+"";
        }else{
            time.innerHTML=""+minute+":"+cur%60+"";
         }
      },1000);
}
Copy after login

②Click on the song title to switch between songs;

 //上一曲
  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();
        }
Copy after login

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;i++) {
            audioall[i].style.color="white";
            if(audioall[i]==musicName){
              musicName.style.color="red";
              qingkong();
              reducejindutiao();
              pauseall();
              index=i;
              start();
            }
          }
        }
Copy after login

At the same time the music stops:

//将进度条置0
 function reducejindutiao(){
     clearInterval(timer1);
      fillbar.style.width="0";
 }
Copy after login

Clear all timers:

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

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();
}
Copy after login

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

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

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);
        }
Copy after login

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

相信看了本文案例你已经掌握了方法,更多精彩请关注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 of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Bose Soundbar Ultra launch experience: Home theater right out of the box? Bose Soundbar Ultra launch experience: Home theater right out of the box? Feb 06, 2024 pm 05:30 PM

For as long as I can remember, I have had a pair of large floor-standing speakers at home. I have always believed that a TV can only be called a TV if it is equipped with a complete sound system. But when I first started working, I couldn’t afford professional home audio. After inquiring and understanding the product positioning, I found that the sound bar category is very suitable for me. It meets my needs in terms of sound quality, size and price. Therefore, I decided to go with the soundbar. After careful selection, I selected this panoramic soundbar product launched by Bose in early 2024: Bose home entertainment speaker Ultra. (Photo source: Photographed by Lei Technology) Generally speaking, if we want to experience the "original" Dolby Atmos effect, we need to install a measured and calibrated surround sound + ceiling at home.

VLC Chromecast not working on Windows PC VLC Chromecast not working on Windows PC Mar 26, 2024 am 10:41 AM

Is the VLC Chromecast feature not working on your Windows PC? This issue may be caused by compatibility issues between your Chromecast device and VLC’s casting feature. In this article, we will tell you what you can do in this situation and what to do if VLC renderer cannot find your Chromecast. How to use ChromecastVLC on Windows? To use VLC to cast videos from Windows to Chromecast, follow these steps: Open the media player app and go to the play menu. Navigate to the Renderer option and you will be able to see the Chromecast device detected

Audacity now gets AI audio editing capabilities with Intel OpenVINO plug-in Audacity now gets AI audio editing capabilities with Intel OpenVINO plug-in Feb 15, 2024 am 11:06 AM

Audacity is a free and open source cross-platform audio editing software. It has an open code and plug-in contribution mechanism, and anyone can participate. In addition, Intel offers a free set of OpenVINOAI plug-ins designed for music editors and podcast producers. This website noticed that the plug-in package is about 2GB in size and can be downloaded on Intel's GitHub page. It also requires the 64-bit Windows version of Audacity to run. The most intuitive thing about this AI plug-in is that it brings three advanced tools to the Audacity music editing function: The first is the "music generation" function. Users can use text to describe the music they want, and AI will generate music clips within 60 seconds to facilitate advertising. and film music

Win10 player progress bar does not move Win10 player progress bar does not move Feb 12, 2024 am 08:12 AM

The October update version of Windows 10v1809 is heading towards the worst Windows upgrade in history without hesitation. Not only was it urgently withdrawn after its first official release, but it was still full of bugs after being rebuilt for a month, making people doubt Microsoft's quality control. Getting more and more worried. Now, it has one more bug on its list, and this time it’s Microsoft’s own media player, Windows Media Player. Recently, some netizens have reported that after installing the latest patch, Windows Media Player in Windows 10v1809 has an issue where the playback progress bar cannot be dragged. No solution has been found yet. Microsoft has confirmed a bug involving two patches for KB4

How to add local music to soda music How to add local music to soda music Feb 23, 2024 pm 07:13 PM

How to add local music to Soda Music? You can add your favorite local music to Soda Music APP, but most friends don’t know how to add local music. Next is the graphic tutorial on how to add local music to Soda Music brought by the editor. , interested users come and take a look! Tutorial on using soda music. How to add local music to soda music. 1. First open the soda music APP and click on the [Music] function area at the bottom of the main page; 2. Then enter the play page and click the [three dots] icon in the lower right corner; 3. Finally Expand the function bar below and select the [Download] button to add it to local music.

Choosing the right tablet for music students Choosing the right tablet for music students Jan 10, 2024 pm 10:09 PM

Which tablet is suitable for musicians? The 12.9-inch speaker in Huawei’s iPad is a very good product. It comes with four speakers and the sound is excellent. Moreover, it belongs to the pro series, which is slightly better than other styles. Overall, ipad pro is a very good product. The speaker of this mini4 mobile phone is small and the effect is average. It cannot be used to play music externally, you still need to rely on headphones to enjoy music. Headphones with good sound quality will have a slightly better effect, but cheap headphones worth thirty or forty yuan cannot meet the requirements. What tablet should I use for electronic piano music? If you want to buy an iPad larger than 10 inches, I recommend using two applications, namely Henle and Piascore. Provided by Henle

Detailed steps to view your favorite music on Douyin Detailed steps to view your favorite music on Douyin Mar 26, 2024 pm 06:20 PM

1. Click [+]. 2. Click [Select Music] above. 3. Click [My Favorites]. Method 2: 1. Open Douyin and click [Me]. 2. Click [Collect] next to the avatar. 3. Click [Music]

How to play music on WeChat How to play music on WeChat Feb 23, 2024 pm 09:28 PM

How to play music on WeChat? You can play your favorite music on WeChat APP, but most friends don’t know how to play their favorite music on WeChat. Next is the graphic tutorial on how to play music on WeChat brought by the editor. Interested users come and take a look! WeChat usage tutorial: How to play music on WeChat 1. First open the WeChat APP, slide down from the top to enter the mini program page; 2. Then click [Music] as shown by the arrow in the picture below; 3. Then in the interface as shown below, enter the search box Enter your favorite song title; 4. Finally, select the corresponding song title and click to play the song.

See all articles