-
Notifications
You must be signed in to change notification settings - Fork 27
/
spectrogram.html
97 lines (87 loc) · 2.65 KB
/
spectrogram.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>martinmelhus.com - Web Audio Encoder</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<style>
body {
background: #333;
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: hidden;
}
canvas {
background: #000;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="overlay">
<button>Start</button>
</div>
<canvas></canvas>
<script>
document.querySelector(".overlay > button").addEventListener("click", (e) => {
let overlay = e.currentTarget.parentNode;
overlay.parentNode.removeChild(overlay);
startSpectrogram();
})
function startSpectrogram() {
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d')
let WIDTH = +canvas.width;
let HEIGHT = +canvas.height;
/* responsive full screen canvas */
let resizeTimeout = null;
const resizeCanvas = () => {
canvas.setAttribute('width', canvas.parentNode.offsetWidth);
canvas.setAttribute('height', canvas.parentNode.offsetHeight);
WIDTH = +canvas.width;
HEIGHT = +canvas.height;
};
resizeCanvas();
window.addEventListener('resize', (e) => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeCanvas, 100);
});
const shiftUp = () => {
let imageData = ctx.getImageData(0, 1, WIDTH, HEIGHT);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.putImageData(imageData, 0, 0);
}
let audioContext = new AudioContext();
let analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
analyser.smoothingTimeConstant = 0.0;
let buffer = new Uint8Array(analyser.frequencyBinCount);
// connect nodes
navigator.mediaDevices.getUserMedia({audio: true})
.then(stream => {
var microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
})
.catch(err => { alert("Microphone is required."); });
const draw = () => {
shiftUp()
analyser.getByteFrequencyData(buffer);
let dx = parseInt(Math.ceil(WIDTH / buffer.byteLength));
buffer.forEach((x, i) => {
let alpha = x / 256.0;
ctx.fillStyle = `rgba(100, 255, 100, ${alpha})`;
ctx.fillRect(i*dx, HEIGHT - 1, dx, 1);
});
let loop = requestAnimationFrame(draw);
}
draw();
}
</script>
</body>
</html>