绘制音乐的频谱图(使用Analyser节点)(转)
<canvas id="canvas" width="400" height="100"></canvas><br/> <input type="button" onclick="audio.play()" value="播放" /> <input type="button" onclick="audio.pause()" value="暂停" /> <script> canvas.style.border="1px solid #CCC"; var AudioContext=AudioContext||webkitAudioContext; var context=new AudioContext; //加载媒体 var audio=new Audio("SuperMario.mp3"); //创建节点 var source=context.createMediaElementSource(audio); var analyser=context.createAnalyser(); //连接:source → analyser → destination source.connect(analyser); analyser.connect(context.destination); //Canvas初始化 var width=canvas.width,height=canvas.height; var g=canvas.getContext("2d"); g.translate(0.5,0.5); //计算出采样比率44100所需的缓冲区长度 var length=analyser.frequencyBinCount*44100/context.sampleRate|0; //创建数据 var output=new Uint8Array(length); //播放帧 (function callee(e){ analyser.getByteFrequencyData(output); //将缓冲区的数据绘制到Canvas上 g.clearRect(-0.5,-0.5,width,height); g.beginPath(),g.moveTo(0,height); for(var i=0;i<width;i++) g.lineTo(i,height-height*output[Math.round(length*i/width)]/255); g.lineTo(i,height),g.fill(); //请求下一帧 requestAnimationFrame(callee); })(); //播放 audio.play(); </script>
相关推荐
jinxiutong 2020-07-26
northwindx 2020-05-31
jinxiutong 2020-05-10
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25