今回はanalyserをつかってオーディオを解析し、Canvasにビジュアライズしてみました。
JavaScript
(function(win, doc) { "use strict"; var canvas = doc.getElementById("canvas"), ctx = canvas.getContext("2d"), request = new XMLHttpRequest(), audioCtx = new AudioContext(); request.onload = function () { audioCtx.decodeAudioData(this.response, function (evt) { var source = audioCtx.createBufferSource(), analyser = audioCtx.createAnalyser(evt); var LENGTH = 64, data = new Uint8Array(LENGTH), w = 0, i = 0; analyser.fftSize = 1024; source.buffer = evt; source.connect(audioCtx.destination); source.connect(analyser); source.loop = true; source.start(); setInterval(function() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillStyle = "#3e3e3e"; w = canvas.width / LENGTH, analyser.getByteFrequencyData(data); for (i = 0; i < LENGTH; ++i) { ctx.rect(i * w, canvas.height - data[i], w, data[i]); } ctx.fill(); }, 1000 / 24); }); }; request.open("GET", "http://jsrun.it/assets/u/L/S/o/uLSoy.mp3", true); request.responseType = "arraybuffer"; request.send(); })(this, document);
HTML
<canvas id="canvas"></canvas>
CSS
* { margin: 0; padding: 0; } body { background: #e3e3e3; overflow: hidden; }