-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
187 lines (153 loc) · 6.09 KB
/
Copy pathscript.js
File metadata and controls
187 lines (153 loc) · 6.09 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
const startBtn = document.getElementById('start-btn');
const dbValue = document.getElementById('db-value');
const thresholdSlider = document.getElementById('threshold-slider');
const thresholdDisplay = document.getElementById('threshold-display');
const gaugeValuePath = document.querySelector('.gauge-value');
const alertModal = document.getElementById('alert-modal');
const closeModalBtn = document.getElementById('close-modal-btn');
const modalThresholdSpan = document.getElementById('modal-threshold');
const micSelect = document.getElementById('mic-select');
async function populateMicList() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const audioDevices = devices.filter(device => device.kind === 'audioinput');
// Save currently selected value to restore it
const selectedValue = micSelect.value;
micSelect.innerHTML = '';
if (audioDevices.length === 0) {
const option = document.createElement('option');
option.value = "";
option.text = "No microphone found";
micSelect.appendChild(option);
return;
}
audioDevices.forEach((device, index) => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || `Microphone ${index + 1}`;
micSelect.appendChild(option);
});
// Restore selection if possible
if (selectedValue && Array.from(micSelect.options).some(opt => opt.value === selectedValue)) {
micSelect.value = selectedValue;
}
} catch (err) {
console.error('Error fetching devices:', err);
}
}
// Request device list on load
populateMicList();
let audioContext;
let analyser;
let microphone;
let dataArray;
let isRecording = false;
let animationId;
let currentThreshold = parseInt(thresholdSlider.value);
let isModalOpen = false;
// Initialize SVG Gauge
// Path is: M 10,45 A 40,40 0 0,1 90,45
// This is exactly a half circle with radius 40
const gaugeCircumference = Math.PI * 40;
gaugeValuePath.style.strokeDasharray = gaugeCircumference;
gaugeValuePath.style.strokeDashoffset = gaugeCircumference;
thresholdSlider.addEventListener('input', (e) => {
currentThreshold = parseInt(e.target.value);
thresholdDisplay.textContent = currentThreshold;
modalThresholdSpan.textContent = currentThreshold;
});
startBtn.addEventListener('click', async () => {
if (isRecording) {
stopMicrophone();
} else {
await startMicrophone();
}
});
closeModalBtn.addEventListener('click', () => {
alertModal.classList.remove('show');
// Cooldown before allowing it to open again to prevent instant re-trigger
setTimeout(() => {
isModalOpen = false;
}, 2000);
});
async function startMicrophone() {
try {
const selectedDeviceId = micSelect.value;
const constraints = {
audio: selectedDeviceId ? { deviceId: { exact: selectedDeviceId } } : true
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
// Re-populate list to get real device names if they were hidden before permission
populateMicList();
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 1024;
microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
dataArray = new Uint8Array(analyser.frequencyBinCount);
isRecording = true;
startBtn.textContent = 'Stop Microphone';
startBtn.classList.add('active');
updateMeter();
} catch (err) {
console.error('Error accessing microphone:', err);
alert('Please allow microphone access to use the decibel meter. Note: Microphone API usually requires HTTPS or localhost.');
}
}
function stopMicrophone() {
isRecording = false;
cancelAnimationFrame(animationId);
if (audioContext && audioContext.state !== 'closed') {
audioContext.close();
}
startBtn.textContent = 'Start Microphone';
startBtn.classList.remove('active');
updateDisplay(0);
}
function updateMeter() {
if (!isRecording) return;
// Get time-domain data to calculate RMS (Root Mean Square)
analyser.getByteTimeDomainData(dataArray);
let sumSquares = 0;
for (let i = 0; i < dataArray.length; i++) {
// Convert byte value (0-255) to a normalized range (-1 to 1)
let normalizedValue = (dataArray[i] - 128) / 128.0;
sumSquares += normalizedValue * normalizedValue;
}
let rms = Math.sqrt(sumSquares / dataArray.length);
// Convert RMS to Decibels
// Adding 100 is an approximation to map dBFS to a positive dB range for UI visualization
let dbFS = 20 * Math.log10(Math.max(rms, 0.0001));
let db = Math.round(dbFS + 100);
// Clamp values between 0 and 120
db = Math.max(0, Math.min(120, db));
// Smooth out the UI updates slightly
let currentDbText = parseInt(dbValue.textContent) || 0;
let smoothDb = Math.round(currentDbText + (db - currentDbText) * 0.3);
updateDisplay(smoothDb);
checkThreshold(smoothDb);
animationId = requestAnimationFrame(updateMeter);
}
function updateDisplay(db) {
dbValue.textContent = db;
// Update gauge path (offset goes from circumference to 0)
let fillPercentage = Math.min(db / 120, 1);
let offset = gaugeCircumference - (fillPercentage * gaugeCircumference);
gaugeValuePath.style.strokeDashoffset = offset;
// Update colors based on threshold
gaugeValuePath.classList.remove('warn', 'danger');
if (db >= currentThreshold) {
gaugeValuePath.classList.add('danger');
} else if (db >= currentThreshold * 0.8) {
gaugeValuePath.classList.add('warn');
}
}
function checkThreshold(db) {
if (db >= currentThreshold && !isModalOpen) {
showModal();
}
}
function showModal() {
isModalOpen = true;
alertModal.classList.add('show');
}