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 barto 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>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;i++) {
audioall[i].style.color="white";
}
audioall[index].style.color="red";
}
}
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: //圖片旋轉(zhuǎn),每30毫米旋轉(zhuǎn)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
currenttime 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);//秒數(shù) ????????var?temp=cur; ???????minute=parseInt(temp/60); ???????if(cur%60<10){ time.innerHTML=""+minute+":0"+cur%60+""; }else{ time.innerHTML=""+minute+":"+cur%60+""; } },1000); }
②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(); ????????}
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(); ????????????} ??????????} ????????}
At the same time the music stops:
//將進度條置0 ?function?reducejindutiao(){ ?????clearInterval(timer1); ??????fillbar.style.width="0"; ?}
Clear all timers:
?function?qingkong(){//清空所有的計時器 ????imagePause(); ????clearInterval(timer2); ?}
3點擊進度條調(diào)整播放進度及音量
首先應該理清一下邏輯:當點擊進度條的時候,滾動條的寬度應該跟鼠標的offsetX一樣長,然后根據(jù)進度條的長度來調(diào)整聽該顯示的時間。
(1) 給滾動條的p添加一個事件,當滾動條長度變化的時候歌曲的當前播放的時間調(diào)整,300是滾動條的總長度;
//調(diào)整播放進度 ?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屬性(值為零到一);
?//調(diào)整音量大小 ??function?changeVolume(e){ ????var?x=e.offsetX+20; ????play[index].volume=parseFloat(x/200)*1; ????//改變按鈕的位置 ?????volume3.style.left=""+x+"px"; }
4隨機、循環(huán)播放
循環(huán)播放音樂的時候,直接index++當index的范圍超過歌曲的長度的時候,index=0重新開始。隨機播放的函數(shù)類似,當歌曲播放完畢的時候,隨機產(chǎn)生一個0到play.length的數(shù)字就可以了。
?//隨機播放歌曲 ??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); ????????}
這樣我們整個音樂播放器就完成了,大家可以自己寫一個好看的界面,就更完美了
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注php中文網(wǎng)其它相關(guān)文章!
推薦閱讀:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.

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

With the rise of short video platforms, Kuaishou has become the preferred platform for many people to record their lives and showcase their talents. When publishing your work, adding a suitable piece of music can make it more lively and interesting. So, how to add music to works published by Kuaishou? 1. How to add music to works published by Kuaishou? 1. First, open the Kuaishou APP, click the "+" sign at the bottom of the page, and select the "shoot" or "upload" button to start making short videos. On the editing page, click the "Music" button to enter the music selection interface. On this interface, you can choose music recommended by the system, or click the "My Music" button to import songs from your personal music library. 3. After selecting a piece of music you like, click the "OK" button, and the music will be added to your

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

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

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

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

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.
