-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
70 lines (59 loc) · 2.21 KB
/
index.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
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head>
<body style="margin: 2vw; text-align: center;">
<script src="https://unpkg.com/[email protected]/build/Tone.js"></script>
<video autoplay playsinline id="video" style="width:1; height:1;"></video>
<h1 style="text-align: center;">Light Theremin</h1>
<canvas style="display: block; border: 1px solid black; width: 96vw; image-rendering: auto; image-rendering: crisp-edges; image-rendering: pixelated;" id="canvas" width="20" height="20"></canvas>
<button style="margin: 10vw 23vw 2vw 23vw; width: 50vw; height: 50px; font-size: 25px;" id="play">Play</button>
<span id="span"></span>
<script>
let pitchShift;
const url = "https://cdn.freesound.org/previews/361/361269_69312-lq.mp3";
//const url = "https://cdn.pixabay.com/audio/2022/03/20/audio_c2901d1f16.mp3";
let max = 0;
let min = 9999999;
const video = document.querySelector("video#video");
const canvas = document.querySelector("canvas#canvas");
const span = document.querySelector("span#span");
const btn = document.querySelector("button#play");
btn.addEventListener("click", async () => {
video.srcObject = await navigator.mediaDevices.getUserMedia({video: true});
await new Promise(r => video.onloadedmetadata = r);
await Tone.start();
const player = new Tone.Player({
url,
loop: true,
autostart: false,
});
await Tone.loaded();
pitchShift = new Tone
.PitchShift({pitch: 0})
.toDestination();
player.connect(pitchShift);
player.start();
const ctx = canvas.getContext("2d");
requestAnimationFrame(function loop() {
ctx.drawImage(video, 0, 0, 20, 20);
let sum = 0;
for (let x=0; x<20; x++) {
for (let y=0; y<20; y++) {
const data = ctx.getImageData(x, y, 1, 1).data;
sum += data[0] + data[1] + data[2];
}
}
if (sum > max) max = sum;
if (sum < min && sum != 0) min = sum;
if (max > min) {
const num = (sum - min)/(max - min) * 10 - 1;
span.innerText = num.toString();
pitchShift.pitch = num;
}
requestAnimationFrame(loop);
});
});
</script>
</body>
</html>