闲来无事做了个h5的音乐可视化,下面上主要部分的代码。包含部分audiocontext api的注释。audiocontext api部分,相当于房子的原材料。
musicvisualizer.ac = new(window.audiocontext || window.webkitaudiocontext)();
//实例化一个音频类型window.audiocontext,后面是为了兼容chrome浏览器
function musicvisualizer(obj) {
this.source = null; //初始化音频资源变量
this.analyser = musicvisualizer.ac.createanalyser(); //这一步是非常重要的,createanalyser()可以创建一个/analysernode/用来获取音频的各项数据,实现音乐可视化
this.size = obj.size; //这里是 index.js里面实例化原型的参数obj中的大小属性
this.analyser.fftsize = this.size * 2;
//fftsize(analysernode的一个属性)是一个无符号长整型的值, 用于确定频域的 fft (快速傅里叶变换) 的大小.fftsize 属性的值必须是从32到32768范围内的2的非零幂;
其默认值为2048.总之最后获取到的数组长度应该是fftsize值的一半,还应该保证它是以2为底的幂。
this.xhr = new xmlhttprequest();//这个就很熟悉了对于大家而言,创建ajax对象
this.analyser.connect(musicvisualizer.ac.destination);
//musicvisualizer.ac.destination是音频要最终输出的目标,所有节点中的最后一个节点应该再连接到musicvisualizer.ac.destination播放声音
this.visualizer = obj.visualizer;
//这里是 index.js里面实例化原型的参数obj中的canvas绘画音乐节点实现节奏可视化
this.visualize();
}
musicvisualizer.prototype.load = function(url, fun) {
this.xhr.abort();//停止正在进行的ajax请求
this.xhr.open("get", url);
this.xhr.responsetype = "arraybuffer";
var self = this;
this.xhr.onload = function() {
fun(self.xhr.response);
};
this.xhr.send();
};
musicvisualizer.prototype.decode = function(arraybuffer, fun) {
musicvisualizer.ac.decodeaudiodata(arraybuffer, function(buffer) {
//decodeaudiodata用于异步解码音频文件中的arraybuffer数据
fun(buffer);
}, function(err) {
console.log(err);
});
};
musicvisualizer.prototype.stop = function() {
this.source[this.source.stop ? "stop" : "noteoff"](0);
};
musicvisualizer.prototype.visualize = function() {
var arr = new uint8array(this.analyser.frequencybincount);
//frequencybincount通常是可视化数据值的数量,为fftsize的一半
requestanimationframe = window.requestanimationframe || webkitrequestanimationframe || mozrequestanimationframe;
//window.requestanimationframe() 方法告诉浏览器您希望执行动画,并请求浏览器调用指定的函数在下一次重绘之前更新动画。该方法将在重绘之前调用的回调作为参数。
var self = this;
function v() {
self.analyser.getbytefrequencydata(arr);
//getbytefrequmencydata把当前频率数据复制到传入其中的uint8array
self.visualizer(arr);
requestanimationframe(v);
}
requestanimationframe(v);
};
musicvisualizer.prototype.play = function(url) {
var self = this;
this.source && this.stop();
this.load(url, function(arraybuffer) {
self.decode(arraybuffer, function(buffer) {
var bs = musicvisualizer.ac.createbuffersource();
//createbuffersource()
方法用于创建一个新的audiobuffersourcenode接口, 该接口可以通过audiobuffer 对象来播放音频数据.
audiobuffer对象可以通过audiocontext.createbuffer 来创建或者通过 audiocontext.decodeaudiodata成功解码音轨后获取.
bs.connect(self.analyser);
bs.buffer = buffer;
bs[bs.start ? "start" : "noteon"](0);
self.source = bs;
});
});
};
h5 canvas可视化部分。原材料的粘合剂
var size = 64;
var box = $("#box")[0];
var height, width;
var canvas = document.createelement('canvas');
var ctx = canvas.getcontext("2d");
box.appendchild(canvas);
var dots = [];
draw.type = "column";
window.onresize = resize;
var line;
var mv = new musicvisualizer({
size: size,
visualizer: draw
});
var clickmusic = (function () {
var lis = $(".music li");
lis.click(function() {
var i = $(this).index();
lis.css('color', 'white');
lis.eq(i).css('color', 'grey');
mv.play('./musics/' + lis.eq(i).html());
});
})();
function random(m, n) {
return math.round(math.random() * (n - m) + m);
}
function getdots() {
dots = [];
for (var i = 0; i < size; i++) {
var x = random(0, width);
var y = random(0, height);
var color = "rgba(" + random(0, 255) + "," + random(0, 255) + "," + random(0, 255) + ",0)";
dots.push({
x: x,
y: y,
color: color,
cap: 0,
dx: random(1, 4)
});
};
}
var resize = (function () {
height = box.clientheight;
width = box.clientwidth;
canvas.height = height;
canvas.width = width;
line = ctx.createlineargradient(0, 0, 0, height);
line.addcolorstop(0, "pink");
line.addcolorstop(0.5, "grey");
line.addcolorstop(1, "lightblue");
getdots();
})();
function draw(arr) {
ctx.clearrect(0, 0, width, height);
var w = width / size;
var cw = w * 0.6;
var ch = cw;
ctx.fillstyle = line;
for (var i = 0; i < size; i++) {
var o = dots[i];
if (draw.type == "column") {
var h = arr[i] / 256 * height;
ctx.fillrect(w * i, height - h, cw, h);
ctx.fillrect(w * i, height - (o.cap + ch), cw, ch);
o.cap--;
if (o.cap < 0) {
o.cap = 0;
}
if (h > 0 && o.cap < h + 30) {
o.cap = h + 30 > height - ch ? height - ch : h + 30;
}
} else if (draw.type == "dot") {
ctx.beginpath();
var r = 10 + arr[i] / 256 * (height > width ? width : height) / 10;
ctx.arc(o.x, o.y, r, 0, math.pi * 2, true);
var circle = ctx.createradialgradient(o.x, o.y, 0, o.x, o.y, r);
circle.addcolorstop(0, "white");
circle.addcolorstop(1, o.color);
ctx.fillstyle = circle;
ctx.fill();
o.x += o.dx;
o.x = o.x > width ? 0 : o.x;
}
}
}
var changestyle = (function () {
var spans = $(".musiclist span");
spans.click(function() {
var i = $(this).index();
spans.removeclass('selected')
.eq(i).addclass('selected');
draw.type = spans.eq(i).attr('type');
});
})();
以上就是html5音乐可视化代码详解的详细内容。