-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.html
91 lines (85 loc) · 2.87 KB
/
memory.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
<html>
<head>
<style>
body {
padding: 0;
margin: 0;
background: black;
}
canvas {
display: block;
width: 100%;
opacity: .7;
}
audio {
width: 100%;
position: fixed;
bottom: 0;
background: black;
}
</style>
</head>
<body>
<div id="container">
<canvas height="256" width="1024" id="vis"></canvas>
</div>
<audio id="audio" src="guitar.mp3" preload controls autoplay></audio>
<script>
// See http://bit.ly/fxq7EY
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element){
window.setTimeout(callback, 1000 / 60);
};
})();
</script>
<script>
var audioElement = document.getElementById('audio');
var canvas = document.getElementById('vis');
var CANVAS_HEIGHT = canvas.height;
var CANVAS_WIDTH = canvas.width;
var ctx = canvas.getContext('2d');
var audioContext = new webkitAudioContext();
var analyser = audioContext.createAnalyser();
var freqData = new Uint8Array(analyser.frequencyBinCount); //1024
ctx.fillStyle = "#fff";
analyser.smoothingTimeConstant = 0.9;
window.onload = init;
audioElement.addEventListener('play', draw);
var pixels = new Array(CANVAS_WIDTH);
for (var x = 0; x < CANVAS_WIDTH; x++) {
pixels[x] = new Array(CANVAS_HEIGHT);
for (var y = 0; y < CANVAS_HEIGHT; y++)
pixels[x][y] = {r:0, g:0, b:0};
}
/* stream goes from audioElement to analyser to speakers */
function init() {
var source = audioContext.createMediaElementSource(audioElement);
source.connect(analyser);
analyser.connect(audioContext.destination);
}
/* draw a single animation frame */
function draw() {
requestAnimFrame(draw, canvas);
analyser.getByteFrequencyData(freqData);
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
for (var i = 0; i < freqData.length; i++) {
var pixel = pixels[i][CANVAS_HEIGHT - freqData[i] - 1];
pixel.r+= 50;
if (pixel.r >= 255)
pixel.g+= 50;
if (pixel.g >= 255)
pixel.b+= 50;
ctx.fillStyle = "rgba(" + pixel.r + "," + pixel.g + "," + pixel.b + ",255)";
ctx.fillRect(i, CANVAS_HEIGHT - freqData[i], 1, 1);
ctx.fillStyle = "rgba(255,255,255,0.1)";
ctx.fillRect(i, CANVAS_HEIGHT - freqData[i] + 1, 1, freqData[i]);
};
}
</script>
</body>
</html>