AnalyserNode#getFloatTimeDomainData
HTML
<button id="test">test</button>
<div><canvas id="canvas"></canvas></div>
CSS
#canvas {
margin: 5px 0;
width: 100%;
height : 128px;
background: #000;
}
JavaScript
// test
var AudioContext = window.AudioContext || window.webkitAudioContext;
var app = (function() {
var app = {};
var osc, amp, ana;
var canvas = document.getElementById("canvas");
var context;
var timerId;
canvas.width = 256;
canvas.height = 128;
context = canvas.getContext("2d");
context.fillStyle = "#000";
app.audioContext = new AudioContext();
app.isPlaying = false;
app.start = function() {
if (app.isPlaying) {
return;
}
app.isPlaying = true;
osc = app.audioContext.createOscillator();
amp = app.audioContext.createGain();
ana = app.audioContext.createAnalyser();
osc.start(app.audioContext.currentTime);
amp.gain.value = 2;
ana.fftSize = 256;
osc.connect(amp);
amp.connect(ana);
ana.connect(app.audioContext.destination);
function calcY(y) {
return canvas.height * 0.5 - (y * canvas.height * 0.25);
}
function line(x1, y1, x2, y2) {
context.beginPath();
context.moveTo(x1|0, y1|0);
context.lineTo(x2|0, y2|0);
context.stroke();
}
var array = new Float32Array(256);
timerId = setInterval(function() {
requestAnimationFrame(function() {
ana.getFloatTimeDomainData(array);
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "#ccc";
line(0, calcY(0), canvas.width, calcY(0));
line(0, calcY(-1), canvas.width, calcY(-1));
line(0, calcY(+1), canvas.width, calcY(+1));
context.strokeStyle = "#0f0";
context.beginPath();
for (var i = 0, imax = array.length; i< imax; i++) {
var x = (i / imax) * canvas.width;
...