You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.1 KiB
62 lines
2.1 KiB
2 years ago
|
|
||
|
JMshake.prototype.canvas = null;
|
||
|
JMshake.prototype.stop = false;
|
||
|
function JMshake(canvas,audio){
|
||
|
this.canvas = canvas;//canvas
|
||
|
this.audio = audio;
|
||
|
}
|
||
|
JMshake.prototype.init = function(){
|
||
|
|
||
|
}
|
||
|
JMshake.prototype.eventBing = function(){
|
||
|
|
||
|
}
|
||
|
JMshake.prototype.loadMusic = function(){
|
||
|
var that = this;
|
||
|
var context = that.canvas.getContext("2d");
|
||
|
var WIDTH = that.canvas.width;
|
||
|
var HEIGHT = that.canvas.height;
|
||
|
|
||
|
//part3: 分析器
|
||
|
var AudCtx = new AudioContext();//音频内容
|
||
|
var analyser = AudCtx.createAnalyser();
|
||
|
var src = AudCtx.createMediaElementSource(that.audio);
|
||
|
src.connect(analyser);
|
||
|
analyser.connect(AudCtx.destination);
|
||
|
analyser.fftSize = 512;//快速傅里叶变换, 必须为2的N次方
|
||
|
var bufferLength = analyser.frequencyBinCount;// = fftSize * 0.5
|
||
|
|
||
|
//part4: 变量
|
||
|
var barWidth = 3;//间隔1px
|
||
|
var barHeight;
|
||
|
var dataArray = new Uint8Array(bufferLength);//8位无符号定长数组
|
||
|
|
||
|
//part5: 动态监听
|
||
|
function renderFrame() {
|
||
|
context.fillStyle = 'rgba(255, 255, 255, 0)';
|
||
|
context.clearRect(0, 0, WIDTH, HEIGHT);
|
||
|
context.fillRect(0, 0, WIDTH, HEIGHT);//画布拓展全屏,动态调整
|
||
|
analyser.getByteFrequencyData(dataArray);//获取当前时刻的音频数据
|
||
|
//part6: 绘画声压条
|
||
|
var x = 0;
|
||
|
for (var i = 0; i < bufferLength; i++) {
|
||
|
var data = dataArray[i];//int,0~255
|
||
|
var percentV = data / 255;//纵向比例
|
||
|
var percentH = i / bufferLength;//横向比例
|
||
|
barHeight = HEIGHT * percentV;
|
||
|
var r = 255 * percentV;//值越大越红
|
||
|
var g = 255 * percentH;//越靠右越绿
|
||
|
var b = 50;
|
||
|
context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
|
||
|
x = i*barWidth;//间隔1px
|
||
|
context.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
|
||
|
}
|
||
|
that.animation = requestAnimationFrame(renderFrame);
|
||
|
}
|
||
|
that.audio.oncanplaythrough = function Draw() {
|
||
|
window.cancelAnimationFrame(that.animation);
|
||
|
delete that.animation;
|
||
|
renderFrame();
|
||
|
}
|
||
|
|
||
|
}
|