原生JavaScript实现一个音乐播放器代码
Admin 2021-04-09 群英技术资讯 1227 次浏览
这篇文章就是主要介绍用原生JavaScript来实现一个简易的音乐播放器,其功能效果包括播放的控制,音乐进度条的控制,歌词的显示和高亮以及播放模式的设置。感谢的朋友就继续往下看吧。
按照播放器的功能划分,对播放器的属性和DOM元素归类,实现同一功能的元素和属性保存在同一对象中,便于管理和操作
const control = { //存放播放器控制 play: document.querySelector('#myplay'), ... index: 2,//当前播放歌曲序号 ... } const audioFile = { //存放歌曲文件及相关信息 file: document.getElementsByTagName('audio')[0], currentTime: 0, duration: 0, } const lyric = { // 歌词显示栏配置 ele: null, totalLyricRows: 0, currentRows: 0, rowsHeight: 0, } const modeControl = { //播放模式 mode: ['顺序', '随机', '单曲'], index: 0 } const songInfo = { // 存放歌曲信息的DOM容器 name: document.querySelector('.song-name'), ... }
功能:控制音乐的播放和暂停,上一首,下一首,播放完成及相应图标修改
audio所用API:audio.play() 和 audio.pause()和audio ended事件
// 音乐的播放和暂停,上一首,下一首控制 control.play.addEventListener('click',()=>{ control.isPlay = !control.isPlay; playerHandle(); } ); control.prev.addEventListener('click', prevHandle); control.next.addEventListener('click', nextHandle); audioFile.file.addEventListener('ended', nextHandle); function playerHandle() { const play = control.play; control.isPlay ? audioFile.file.play() : audioFile.file.pause(); if (control.isPlay) { //音乐播放,更改图标及开启播放动画 play.classList.remove('songStop'); play.classList.add('songStart'); control.albumCover.classList.add('albumRotate'); control.albumCover.style.animationPlayState = 'running'; } else { //音乐暂停,更改图标及暂停播放动画 ... } } function prevHandle() { // 根据播放模式重新加载歌曲 const modeIndex = modeControl.index; const songListLens = songList.length; if (modeIndex == 0) {//顺序播放 let index = --control.index; index == -1 ? (index = songListLens - 1) : index; control.index = index % songListLens; } else if (modeIndex == 1) {//随机播放 const randomNum = Math.random() * (songListLens - 1); control.index = Math.round(randomNum); } else if (modeIndex == 2) {//单曲 } reload(songList); } function nextHandle() { const modeIndex = modeControl.index; const songListLens = songList.length; if (modeIndex == 0) {//顺序播放 control.index = ++control.index % songListLens; } else if (modeIndex == 1) {//随机播放 const randomNum = Math.random() * (songListLens - 1); control.index = Math.round(randomNum); } else if (modeIndex == 2) {//单曲 } reload(songList); }
功能:实时更新播放进度,点击进度条调整歌曲播放进度
audio所用API:audio timeupdate事件,audio.currentTime
// 播放进度实时更新 audioFile.file.addEventListener('timeupdate', lyricAndProgressMove); // 通过拖拽调整进度 control.progressDot.addEventListener('click', adjustProgressByDrag); // 通过点击调整进度 control.progressWrap.addEventListener('click', adjustProgressByClick);
播放进度实时更新:通过修改相应DOM元素的位置或者宽度进行修改
function lyricAndProgressMove() { const audio = audioFile.file; const controlIndex = control.index; // 歌曲信息初始化 const songLyricItem = document.getElementsByClassName('song-lyric-item'); if (songLyricItem.length == 0) return; let currentTime = audioFile.currentTime = Math.round(audio.currentTime); let duration = audioFile.duration = Math.round(audio.duration); //进度条移动 const progressWrapWidth = control.progressWrap.offsetWidth; const currentBarPOS = currentTime / duration * 100; control.progressBar.style.width = `${currentBarPOS.toFixed(2)}%`; const currentDotPOS = Math.round(currentTime / duration * progressWrapWidth); control.progressDot.style.left = `${currentDotPOS}px`; songInfo.currentTimeSpan.innerText = formatTime(currentTime); }
拖拽调整进度:通过拖拽移动进度条,并且同步更新歌曲播放进度
function adjustProgressByDrag() { const fragBox = control.progressDot; const progressWrap = control.progressWrap drag(fragBox, progressWrap) } function drag(fragBox, wrap) { const wrapWidth = wrap.offsetWidth; const wrapLeft = getOffsetLeft(wrap); function dragMove(e) { let disX = e.pageX - wrapLeft; changeProgressBarPos(disX, wrapWidth) } fragBox.addEventListener('mousedown', () => { //拖拽操作 //点击放大方便操作 fragBox.style.width = `14px`;fragBox.style.height = `14px`;fragBox.style.top = `-7px`; document.addEventListener('mousemove', dragMove); document.addEventListener('mouseup', () => { document.removeEventListener('mousemove', dragMove); fragBox.style.width = `10px`;fragBox.style.height = `10px`;fragBox.style.top = `-4px`; }) }); } function changeProgressBarPos(disX, wrapWidth) { //进度条状态更新 const audio = audioFile.file const duration = audioFile.duration let dotPos let barPos if (disX < 0) { dotPos = -4 barPos = 0 audio.currentTime = 0 } else if (disX > 0 && disX < wrapWidth) { dotPos = disX barPos = 100 * (disX / wrapWidth) audio.currentTime = duration * (disX / wrapWidth) } else { dotPos = wrapWidth - 4 barPos = 100 audio.currentTime = duration } control.progressDot.style.left = `${dotPos}px` control.progressBar.style.width = `${barPos}%` }
点击进度条调整:通过点击进度条,并且同步更新歌曲播放进度
function adjustProgressByClick(e) { const wrap = control.progressWrap; const wrapWidth = wrap.offsetWidth; const wrapLeft = getOffsetLeft(wrap); const disX = e.pageX - wrapLeft; changeProgressBarPos(disX, wrapWidth) }
功能:根据播放进度,实时更新歌词显示,并高亮当前歌词(通过添加样式)
audio所用API:audio timeupdate事件,audio.currentTime
// 歌词显示实时更新 audioFile.file.addEventListener('timeupdate', lyricAndProgressMove); function lyricAndProgressMove() { const audio = audioFile.file; const controlIndex = control.index; const songLyricItem = document.getElementsByClassName('song-lyric-item'); if (songLyricItem.length == 0) return; let currentTime = audioFile.currentTime = Math.round(audio.currentTime); let duration = audioFile.duration = Math.round(audio.duration); let totalLyricRows = lyric.totalLyricRows = songLyricItem.length; let LyricEle = lyric.ele = songLyricItem[0]; let rowsHeight = lyric.rowsHeight = LyricEle && LyricEle.offsetHeight; //歌词移动 lrcs[controlIndex].lyric.forEach((item, index) => { if (currentTime === item.time) { lyric.currentRows = index; songLyricItem[index].classList.add('song-lyric-item-active'); index > 0 && songLyricItem[index - 1].classList.remove('song-lyric-item-active'); if (index > 5 && index < totalLyricRows - 5) { songInfo.lyricWrap.scrollTo(0, `${rowsHeight * (index - 5)}`) } } }) }
功能:点击跳转播放模式,并修改相应图标
audio所用API:无
// 播放模式设置 control.mode.addEventListener('click', changePlayMode); function changePlayMode() { modeControl.index = ++modeControl.index % 3; const mode = control.mode; modeControl.index === 0 ? mode.setAttribute("class", "playerIcon songCycleOrder") : modeControl.index === 1 ? mode.setAttribute("class", "playerIcon songCycleRandom ") : mode.setAttribute("class", "playerIcon songCycleOnly") }
以上就是用原生JavaScript来实现的音乐播放器示例代码,文中的示例代码很详细,大家能参考上述代码主机动手实现一下。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
微信小程序实现评价功能 本文实例为大家分享了微信小程序实现评价的具体代码,供大家参考,具体内容如下 首先去图标库,找一个空心星图片和一个实星图片 先是效果图 代码 wxml文件 for循环5次,初始值是5星,data-name用于区别是那个评价的星星src="{{item-total+1>0?’…/image/empty_stars.png’:’…/image/entity_stars.png’}}"条件判断,图片判断一个是空星,一个实星,根据自己图片地址改变 <view class=& ...
一文教会你解决js数字精度丢失问题 目录 一.关于为什么要解决精度丢失 二.怎么解决js的计算精度丢失问题? 三.toPrecision 特定方法返回四舍五入长度字符串 结语 一.关于为什么要解决精度丢失 可以看下例子,因为js失去精度问题也是常见的问题,正常我们可以四舍五入或者 toFixed保留小数这种去解决 现在遇到问题是我们明知道计算结果是等于0.01的但是最后的结果确实true,如果我们遇到运算问题,小数数值比对问题,那么我们就必须要去解决他,否则也就会出现上者情况,出现逻辑判断出错问题 二.怎么解决js的计算精度丢失问
目录vue ant design 封装弹窗表单使用ant-design-vue的Form表单使用脚手架新建项目安装并导入ant-design-vue,使用Form组件启动应用,测试验证vue ant design 封装弹窗表单template div id=formForm a-modal
concat()可以基于当前数组中的所有项目创建一个新的数组。这种方法首先创建当前的数组副本,然后将接收到的参数添加到该副本的末尾,最后返回新构建的数组。
js如何查找字符串的最长单词?这篇文章给大家分享是关于基于Free Code Camp基本算法脚本来查找字符串的最长单词,本文会介绍三种方法,是小编比较推荐的,有需要的朋友可以看一看。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008