67 lines
1.6 KiB
JavaScript
67 lines
1.6 KiB
JavaScript
var audio = document.getElementById('audio');
|
|
|
|
let button = document.getElementById('launch-larynx').addEventListener('click', function(){
|
|
loadSound(audio.src);
|
|
render();
|
|
});
|
|
|
|
let audioCtx;
|
|
let source;
|
|
let analyser;
|
|
let canvasCtx = document.getElementById('spectrogram-canvas');
|
|
|
|
let WIDTH = canvasCtx.width;
|
|
let HEIGHT = canvasCtx.height;
|
|
|
|
function loadSound(url) {
|
|
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
source = audioCtx.createMediaElementSource(audio);
|
|
}
|
|
|
|
function render() {
|
|
analyser = audioCtx.createAnalyser();
|
|
|
|
analyser.fftSize = 2048;
|
|
var bufferLength = analyser.frequencyBinCount;
|
|
var dataArray = new Uint8Array(bufferLength);
|
|
analyser.getByteTimeDomainData(dataArray);
|
|
|
|
// draw an oscilloscope of the current audio source
|
|
|
|
function draw() {
|
|
|
|
drawVisual = requestAnimationFrame(draw);
|
|
|
|
analyser.getByteTimeDomainData(dataArray);
|
|
|
|
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
|
|
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
|
|
|
|
canvasCtx.lineWidth = 2;
|
|
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
|
|
|
|
canvasCtx.beginPath();
|
|
|
|
var sliceWidth = WIDTH * 1.0 / bufferLength;
|
|
var x = 0;
|
|
|
|
for (var i = 0; i < bufferLength; i++) {
|
|
|
|
var v = dataArray[i] / 128.0;
|
|
var y = v * HEIGHT / 2;
|
|
|
|
if (i === 0) {
|
|
canvasCtx.moveTo(x, y);
|
|
} else {
|
|
canvasCtx.lineTo(x, y);
|
|
}
|
|
|
|
x += sliceWidth;
|
|
}
|
|
|
|
canvasCtx.lineTo(canvas.width, canvas.height / 2);
|
|
canvasCtx.stroke();
|
|
};
|
|
|
|
draw();
|
|
} |