H5音樂可視化

閒來無事作了個H5的音樂可視化,下面上主要部分的代碼。包含部分AudioContext api的註釋。

  • AudioContext api部分,至關於房子的原材料。css

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可視化部分。原材料的粘合劑html

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');
    });
})();
  • 完整源碼在這裏githubgit

相關文章
相關標籤/搜索