绘制音乐的频谱图(使用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
MIKUScallion 2020-02-22
songfens 2020-01-10
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06