好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

js实现音乐播放器

本文实例为大家分享了js实现音乐播放器的具体代码,供大家参考,具体内容如下

音乐播放的主要js代码

音乐数据的数组对象

想向前端网页提供数据,并且为后面的js代码提供了音乐路径

?{
? ? ? ? ablum: "海阔天空",
? ? ? ? artist: "Beyond",
? ? ? ? id: 1,
? ? ? ? name: "大地",
? ? ? ? path: "musics/1592373302464.mp3",
? ? ? ? size: 4147913,
? ? ? ? style: "摇滚",
? ? ? ? uptime: 1592373302000
? ? },
? ? {
? ? ? ? ablum: "xxx",
? ? ? ? artist: "GALA ",
? ? ? ? id: 2,
? ? ? ? name: "追梦赤子心",
? ? ? ? path: "musics/1592373330188.mp3",
? ? ? ? size: 8357216,
? ? ? ? style: "摇滚",
? ? ? ? uptime: 1592373330000
? ? },
? ? {
? ? ? ? ablum: "123",
? ? ? ? artist: "筷子兄弟",
? ? ? ? id: 3,
? ? ? ? name: "父亲",
? ? ? ? path: "musics/1592373363687.mp3",
? ? ? ? size: 12050851,
? ? ? ? style: "怀旧",
? ? ? ? uptime: 1592373363000
? ? },
? ? {
? ? ? ? ablum: "xxx",
? ? ? ? artist: "Bruno Mars ",
? ? ? ? id: 4,
? ? ? ? name: "Just The Way You Are",
? ? ? ? path: "musics/1592383891287.mp3",
? ? ? ? size: 3602925,
? ? ? ? style: "摇滚",
? ? ? ? uptime: 1592383891000
? ? },
? ? {
? ? ? ? ablum: "xxx",
? ? ? ? artist: "Jason Chen",
? ? ? ? id: 5,
? ? ? ? name: "童话",
? ? ? ? path: "musics/1592383916578.mp3",
? ? ? ? size: 4143707,
? ? ? ? style: "流行",
? ? ? ? uptime: 1592383916000
? ? },

全局变量

//创建音频播放器对象
var player =document.createElement('audio');
//设置当前正在播放的歌曲的索引
var currentIndex=0;
//声明一个标记,记录歌曲的播放状态
var isplay=false;

自调用函数

主要功能是通过循环遍历使用html字符串向前端动态的添加音乐数据,并初始化播放源(currentIndex标记)

(function() {
//绑定数据到页面中
    var html = '';
//循环遍历歌曲列表,根据歌曲数目在页面生成对应的html代码
    for (var i = 0; i < musics.length; i++) {
        var m = musics[i];
        //根据循环的次数创建对应的歌曲项
        html += `<tr class="music-item" data-index="${i}">
                 <td class="tb-space" style="text-align: center"></td>
                 <td><a href="javascript:;">${m.name}</a></td>
                 <td><a href="javascript:;">${m.artist}</a></td>
                 <td><a href="javascript:;">${m.ablum}</a></td>
                 <td>${fmtSize(m.size)}</td>
                 <td class="tb-space"></td>
               </tr>`;
    }
    //将生产html插入到指定的dom节点中
    document.getElementById('tbody').innerHTML = html;
    //初始化播放源
    player.src=musics[currentIndex].path;
})();

添加点击事件

循环遍历的给所有的音乐对象添加点击事件

//为列表项触发点击事件
var trs = document.querySelectorAll('.music-item');
for (var i=0;i<trs.length;i++) {

? ? trs[i].addEventListener('click',function () {
? ? ? ? //清除状态
? ? ? ? clearstatus();
? ? ? ? var index = this.dataset.index;
? ? ? ? //记录当前播放的歌曲索引
? ? ? ? currentIndex=index;
? ? ? ? //获取需要播放的对象
? ? ? ? var m = musics[index];
? ? ? ? //设置播放源
? ? ? ? player.src=m.path;
? ? ? ? startPlay();
? ? })

当然,不可能一次播放多个音乐,所以在播放当前音乐时将上一首音乐清除(封装方法见下)

封装方法

1.清除上一首歌曲方法
2.开始播放方法(同时将全局变量isplay设置为true)
3.暂停播放方法(同时将全局变量isplay设置为false)
4.将总时长s转变成mm:ss
5.将大小B装化为MB

//清除上一首歌的歌曲状态
function clearstatus() {
? ? //还原上一首正在播放的歌曲表的背景颜色
? ? trs[currentIndex].style.background='';
? ? //清除当前行下的第一个单元格的内容(清除图标)
? ? trs[currentIndex].getElementsByTagName('td')[0].innerHTML=''
}
//开始播放
function startPlay() {
? ? //将状态标记为正在播放
? ? isplay=true;
? ? //播放
? ? player.play();
? ? //修改当前行的背景色
? ? trs[currentIndex].style.background='#f0f0f0';
? ? trs[currentIndex].getElementsByTagName('td')[0].innerHTML='<img src="imgs/playing-list.gif" alt="">'
? ? //将播放按钮的背景图片设置为暂停图标
? ? document.getElementById('btnPlay').className='btn-pause';
? ? //将正在播放的歌曲名显示到底部控制区域
? ? document.getElementById('playingName').innerText=musics[currentIndex].name;
}

//暂停播放
function pausePlay(){
? ? isplay=false;
? ? player.pause();
? ? document.getElementById('btnPlay').className='btn-play';
}
//格式化歌曲播放时间 mm:ss
function fmtTime(time) {
? ? time*=1000;
? ? //使用毫秒构建日期对象
? ? time=new Date(time);
? ? var m = time.getMinutes();
? ? var s = time.getSeconds();
? ? m=m<10?'0'+m:m;
? ? s=s<10?'0'+s:s;
? ? return m+':'+s;
}


//大小转化
function fmtSize(size) {
? ? size=size/(1024*1024);
? ? size=size.toFixed(1);
? ? return size+'MB';
}

播放控制按钮

就是暂停和播放按钮
判断全局变量isplay,如果是true说明当前正在播放歌曲,点击就会暂停,反之就会播放

//播放控制
document.getElementById('btnPlay').addEventListener('click',function () {
? ? if (isplay){
? ? ? ? pausePlay();
? ? } else{
? ? ? ? startPlay();
? ? }
});

将当前歌曲的播放时长与总时长在界面上动态改变

//记录歌曲的当前播放时间
var now =0;
//记录歌曲的总播放时长
var total=0;
//当播放器的数据被加载时触发
player.addEventListener('loadeddata',function () {
? ? //获取当前播发器的播放位置以及总播放时长(单位s)
? ? now=player.currentTime;
? ? total=player.duration;
? ? //将歌曲的播放时间显示到控制区域
? ? document.querySelector('.play-current').innerText=fmtTime(now);
? ? document.querySelector('.play-duration').innerText=fmtTime(total);
})

为进度条绑定进度改变事件

原理很简单,通过上面的时间变化求得百分比,设置为进度的百分比就OK了

//为播放器绑定播放进度改变事件
player.addEventListener('timeupdate',updateProgress);
? ? function updateProgress() {
? ? //获取当前的播放进度
? ? now=player.currentTime;
? ? //计算进度的百分比
? ? var p =now/total*100+'%';
? ? document.querySelector('.progress-control').style.width=p;
? ? document.querySelector('.play-current').innerText=fmtTime(now);
}

为播放器绑定播放完成事件以及上下首的切换

同意要清除上一首歌的播放状态,改变全局变量currentIndex就可以实现

//为播放器绑定播放完成事件
player.addEventListener('ended',function () {
? ? //清除上一首播放状态
? ? clearstatus();
? ? currentIndex++;
? ? if(currentIndex>=musics.length){
? ? ? ? currentIndex=0;
? ? }
? ? //重新为播放器设置播放源
? ? player.src=musics[currentIndex].path;
? ? //继续播放
? ? startPlay();
});

//上一首
document.querySelector('.btn-pre').addEventListener('click',function () {
? ? clearstatus();
? ? currentIndex--;
? ? if(currentIndex<0){
? ? ? ? currentIndex=musics.length-1;
? ? }
? ? //重新为播放器设置播放源
? ? player.src=musics[currentIndex].path;
? ? //继续播放
? ? startPlay();

});
//下一首
document.querySelector('.btn-next').addEventListener('click',function () {
? ? clearstatus();
? ? currentIndex++;
? ? currentIndex=currentIndex%musics.length;
? ? //重新为播放器设置播放源
? ? player.src=musics[currentIndex].path;
? ? //继续播放
? ? startPlay();
});

通过进度条控制歌曲播放

对鼠标进行监听,得到鼠标最后的落点,计算出进度条的起始位置与该点占据总长度的比例,然后简单的数学运算,我们知道歌曲总长度就很清楚的得到鼠标落点的歌曲该播放的位置

//改变歌曲的播放进度
(function(box,bar) {
? ? //监听鼠标是否按下
? ? var status=false;
? ? //鼠标按下事件监听
? ? document.querySelector(box).addEventListener('mousedown',function (e) {
? ? ? ? player.removeEventListener('timeupdate',updateProgress);
? ? ? ? move(e);
? ? ? ? status=true;
? ? })

? ? //鼠标抬起事件监听
? ? document.addEventListener('mouseup',function () {
? ? ? ? player.currentTime=now;
? ? ? ? player.addEventListener('timeupdate',updateProgress);
? ? ? ? status=false;
? ? })

? ? //鼠标移动事件监听
? ? document.querySelector(box).addEventListener('mousemove',function (e) {
? ? ? ? if(status==true){
? ? ? ? ? ? move(e)
? ? ? ? }
? ? })

? ? //鼠标滑动执行
? ? function move(e) {
? ? ? ? var eventLeft=e.offsetX;

? ? ? ? var w=window.getComputedStyle(document.querySelector(box)).width;
? ? ? ? var w1=window.getComputedStyle(document.querySelector('.play-current')).width;
? ? ? ? var w2=window.getComputedStyle(document.querySelector('.play-duration')).width;
? ? ? ? w1=parseInt(w1);
? ? ? ? w2=parseInt(w2);
? ? ? ? document.querySelector(bar).style.width=eventLeft+w1+'px';
? ? ? ? now=(eventLeft)/(parseInt(w)-w1-w2)*total;
? ? ? ? status=true;

? ? ? ? // var eventLeft=e.offsetX;
? ? ? ? // document.querySelector(bar).style.width=eventLeft+'px';
? ? ? ? // var w=window.getComputedStyle(document.querySelector(box)).width;
? ? ? ? // now=eventLeft/parseInt(w)*total;
? ? ? ? // status=true;

? ? }
})('.play-length','.progress-control');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于js实现音乐播放器的详细内容...

  阅读:39次