我就不瞎比比了,直接上代码吧:
//获取随机颜色 function randomColor(){ var r = Math.floor(Math.random()*256); var g = Math.floor(Math.random()*256); var b = Math.floor(Math.random()*256); return "rgb("+r+","+g+","+b+")";//IE7不支出rgb }; window.onload = function(){ //给音乐播放器(audio)添加一个timeupdate时间 document.getElementById("music").ontimeupdate = function(){ var currentTime = Math.floor(this.currentTime); //获取当前时间 var m = parseInt(currentTime / 60);//分钟 var s = parseInt(currentTime % 60);//秒钟 var time = (m<10?("0"+m):m)+":"+(s<10?("0"+s):s); //格式化 //console.log(time); //打印出来看看 // 百分比 = 当前时长 ÷ 总时长 × 100% var total = this.duration;//总时长 //console.log(currentTime + '=======' + total); //console.log( Math.floor(currentTime / total * 100) + "%" ); document.getElementsByClassName("progress")[0].style.width = Math.floor(currentTime / total * 100) + "%" ; } //音轨制作 var box = document.getElementsByClassName('mbox')[0]; //获取承载音轨的父盒子 var allWidth = box.clientWidth;//获取承载音轨盒子的宽度 var itemWidth = 5; var len = (allWidth / itemWidth ); //计算一共出现多少条音轨 var html = ''; //动态拼接音轨 for(var i = 0;i < len ; i ++){ html+="<span class='item' style='left:"+(i * itemWidth)+"px;background:"+randomColor()+";'></span>"; } box.innerHTML += html; //添加音轨 var audio = document.getElementById("music"); //1:音频上下文 window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext; /*动画执行的兼容写法*/ window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame; //2:初始化音轨对象 var audioContext = new window.AudioContext(); var flag = null; //控制是否解析的开关变量 //拿到播放器去解析音乐文件 var audioBufferSouceNode = audioContext.createMediaElementSource(audio); audio.onplay = function(){ flag = true; //创建解析对象 var analyser = audioContext.createAnalyser(); parse(analyser,function(array){ console.log(array); //打印解析出来的音轨节点 for(var i = 0;i < len ; i ++){ document.getElementsByClassName('item')[i].style.height = array[i] + 'px'; } }); } audio.onpause = function(){ for(var i = 0;i < len ; i ++){ document.getElementsByClassName('item')[i].style.height = 1 + 'px'; } flag = false; } function parse(analyser,callback){ if(!flag){ return; } audioBufferSouceNode.connect(analyser); analyser.connect(audioContext.destination); var array = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(array); if(callback) callback(array); requestAnimationFrame(function(){ parse(analyser,callback); }); } }
css:
.item { position:absolute; width:5px; height:1px; left:0px; bottom:0px; opacity: 0.5; }
效果:
##总结思路
#####1.获取mbox的宽度,然后动态计算一共有多少条音轨。
#####2.用H5的音频解析器去解析当前音乐播放的各频率的音高
#####3.用这些音高去给每一条音轨动态地设置高度height