Home > Article > Web Front-end > How to implement a music player in native JS
Below I will share with you an example of using native JS to implement synchronized playback of lyrics in a web mobile music player. It has a good reference value and I hope it will be helpful to everyone.
I have sorted it out. I have written it several times before and every time I lost everything. Today I spent a long time to sort out my thoughts and sort out the clues.
//获取歌词文本 var txt = document.getElementById("lrc"); var lrc = txt.value;//获取文本域里的值 /*console.log(lrc);*/ var lrcArr = lrc.split("[");//去除[ /*console.log(lrcArr);*/ var html = "";//定义一个空变量保存文本 for(var i=0 ; i<lrcArr.length ; i++) { var arr = lrcArr[i].split("]"); /*console.log(arr[1]);*/ var allTime = arr[0].split("."); var time = allTime[0].split(":"); //获取分钟 秒钟 把时间换算成秒钟 var timer = time[0]*60 + time[1]*1; var text = arr[1]; if(text) { html += "<p id="+timer+">"+text+"</p>" } con.innerHTML = html <pre class="html" name="code">}
实现歌词同步首先要获取到文本框 再配合H5中新增的属性如图 其实很简单啦!
//监听音乐播发进度实现歌词同步 myMusic.addEventListener("timeupdate",function(){ //获取当前播放时间 var curTime = parseInt(this.currentTime); if(document.getElementById(curTime)) { for(var i=0 ; i<oP.length ; i++) { oP[i].style.cssText = "color:#ccc;font-size:12px;"; } document.getElementById(curTime).style.cssText="color:rgb(242,110,111);font-size:18px;"; if (oP[num+7].id == curTime)//判断成功一次num++ { con.style.top = -20*num +"px"; num++; } } });
The above is what I have compiled for everyone. I hope it will be useful to you in the future. Everyone is helpful.
Related articles:
How to implement the page loading progress bar component in vue
What are the differences between Map and ForEach in JS ?
Use axios to encapsulate the fetch method and call
The above is the detailed content of How to implement a music player in native JS. For more information, please follow other related articles on the PHP Chinese website!