-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.js
More file actions
60 lines (46 loc) · 1.51 KB
/
Copy pathdecoder.js
File metadata and controls
60 lines (46 loc) · 1.51 KB
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
const TONE_FREQ = 1000;
const THRESHOLD = 0.01; // amplitude threshold
let receivedBits = '';
let receivedText = '';
async function startDecoding() {
const audioCtx = new AudioContext();
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
const dataArray = new Uint8Array(analyser.frequencyBinCount);
source.connect(analyser);
let detecting = false;
let startTime = 0;
function detect() {
analyser.getByteTimeDomainData(dataArray);
// simple amplitude detection
let sum = 0;
for (let i = 0; i < dataArray.length; i++) {
sum += Math.abs(dataArray[i] - 128);
}
const amp = sum / dataArray.length;
if (amp > THRESHOLD * 128) {
if (!detecting) {
detecting = true;
startTime = performance.now();
}
} else {
if (detecting) {
const duration = performance.now() - startTime;
receivedBits += duration > 200 ? '1' : '0';
// convert every 8 bits
while (receivedBits.length >= 8) {
const byte = receivedBits.slice(0, 8);
receivedBits = receivedBits.slice(8);
receivedText += String.fromCharCode(parseInt(byte, 2));
document.getElementById('output').innerText = receivedText;
}
detecting = false;
}
}
requestAnimationFrame(detect);
}
detect();
}
document.getElementById('start').onclick = startDecoding;