Home > Web Front-end > JS Tutorial > body text

Make a music player with native JS

php中世界最好的语言
Release: 2018-04-17 14:26:27
Original
5334 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template