-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
414 lines (375 loc) · 16.4 KB
/
index.html
File metadata and controls
414 lines (375 loc) · 16.4 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Audio Recorder — WAV (Stereo)</title>
<meta name="description" content="Record WAV (stereo, 10s max) and upload to Google Drive. Start/Stop toggle, optional Reset. Filename uses userID+gender+age+timestamp." />
<link rel="icon" href="data:,">
<style>
:root { --w: 880px; }
html,body { height: 100%; }
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
margin: 0; padding: 2.5rem 1rem;
display: grid; place-items: start center;
background: #fafafa; color:#111;
}
main {
width: min(var(--w), 100%);
background: white; border: 1px solid #e5e5e5; border-radius: 12px;
padding: 1.25rem 1.25rem 1.5rem; box-shadow: 0 4px 30px rgba(0,0,0,.04);
}
/* Centered header */
.app-header { text-align: center; margin-bottom: .75rem; }
.app-header h1 { margin: .25rem 0 .25rem; font-size: clamp(1.2rem, 1.1rem + 1.2vw, 1.9rem); }
.app-header p.lead { margin: 0; color:#4b5563; }
.row { display:flex; align-items:center; gap:.6rem; margin:.75rem 0; flex-wrap:wrap; }
.col { display:flex; flex-direction:column; gap:.6rem; }
button, .button { appearance: none; border: 0; background:#1f6feb; color:white; padding:.6rem .95rem;
border-radius:8px; font-weight:600; cursor:pointer; text-decoration:none; }
button.secondary { background:#6b7280; }
button.danger { background:#b91c1c; }
button[disabled], .button[aria-disabled="true"] { opacity:.55; cursor:not-allowed; }
#status { font-weight:600; }
#meter { width: 320px; height: 12px; background:#eee; border-radius: 6px; overflow:hidden; border:1px solid #ddd; }
#bar { height: 100%; width: 0%; background:#4a90e2; }
audio { width: 100%; }
.pill { font: 12px/1.8 system-ui; padding:.1rem .5rem; border:1px solid #e5e7eb; border-radius:999px; color:#374151;}
.muted { color:#666; }
input[type="number"], input[type="text"] { padding:.5rem .6rem; border:1px solid #d1d5db; border-radius:8px; }
input#userID { width: 100px; text-transform: uppercase; }
.hr { height:1px; background: repeating-linear-gradient(90deg,#e5e7eb, #e5e7eb 8px, transparent 8px, transparent 16px); margin: 1rem 0; }
.formlabel { font-size:.9rem; color:#374151; }
.options { display:flex; align-items:center; gap:.8rem; }
.options label { display:flex; align-items:center; gap:.25rem; cursor:pointer; }
#countdown { min-width: 4ch; text-align: right; }
/* Instruction line */
.instruction { margin-top: .25rem; font-weight: 700; }
</style>
</head>
<body>
<main>
<!-- Centered header -->
<div class="app-header">
<h1 id="appTitle">Audio Recorder — WAV (Stereo)</h1>
<p id="appSubtitle" class="lead">
Filename: <code>userID_G_AGE_audio_dd_mm_yyyy_hh_mm_ss.wav</code> • Channels: <strong>2</strong> • Max length: <strong>10s</strong>
</p>
</div>
<div class="row" aria-label="metadata">
<label class="formlabel" for="userID">User ID (A123):</label>
<input id="userID" type="text" placeholder="A123" maxlength="4" pattern="[A-Za-z][0-9]{3}" aria-label="User ID one letter + three digits" />
<div class="options">
<span class="formlabel">Gender:</span>
<label><input type="radio" name="gender" value="M" id="gM"> M</label>
<label><input type="radio" name="gender" value="F" id="gF"> F</label>
<label><input type="radio" name="gender" value="X" id="gX"> Other</label>
</div>
<label class="formlabel" for="age">Age:</label>
<input id="age" type="number" placeholder="00" min="0" max="120" step="1" />
</div>
<!-- The ONLY instruction (bold) -->
<p class="instruction"><strong>Hit Start Recording and Say MAAAAAAAAAAAAAAAAAAAP, upload when finished.</strong></p>
<div class="row" aria-label="controls">
<button id="recordToggleBtn">Start recording</button>
<button id="resetBtn" class="danger" disabled>Reset</button>
<span id="status" class="pill">idle</span>
<span id="sr" class="pill"></span>
<span id="countdown" class="pill">10.0s</span>
</div>
<div class="row" aria-label="input-level">
<strong>Input level</strong>
<div id="meter"><div id="bar"></div></div>
</div>
<div class="col" style="align-items:stretch;" aria-label="playback">
<audio id="player" controls></audio>
<div class="row" style="justify-content:space-between;">
<div class="row" style="gap:.5rem;">
<button id="previewBtn" class="secondary" disabled>Preview</button>
<a id="download" class="button" download="recording.wav">Download .wav</a>
</div>
<span id="sizeHint" class="muted"></span>
</div>
</div>
<div class="hr" role="separator"></div>
<div class="col" aria-label="drive-upload">
<button id="uploadBtn" disabled>Upload</button>
</div>
</main>
<script type="module">
/* ===== Optional: customize header text ===== */
const APP_TITLE = 'TalkingSick recording — WAV (Stereo)';
const APP_SUBTITLE = 'Filename: <code>userID_G_AGE_audio_dd_mm_yyyy_hh_mm_ss.wav</code> • Channels: <strong>2</strong> • Max length: <strong>10s</strong>';
document.getElementById('appTitle').textContent = APP_TITLE;
document.getElementById('appSubtitle').innerHTML = APP_SUBTITLE;
/* ===== CONFIG (Drive upload endpoint) ===== */
const WEB_APP_URL = 'https://script.google.com/macros/s/AKfycbz4BwQs2SkQ8Z1C4bG33rDPn1nZG4g_wAvVPYI_soEVXMtNZNDNL0Qf6Szx9jpE__TNNw/exec';
/* ===== State ===== */
let audioCtx, stream, meterRAF;
let leftBuffers = [];
let rightBuffers = [];
let sampleRate = 48000;
let recording = false;
let stopTimer = null;
let countdownRAF = null;
let startTs = 0;
const MAX_SECONDS = 10.0;
/* ===== Elements ===== */
const recordBtn = document.getElementById('recordToggleBtn');
const resetBtn = document.getElementById('resetBtn');
const statusEl = document.getElementById('status');
const srEl = document.getElementById('sr');
const player = document.getElementById('player');
const previewBtn= document.getElementById('previewBtn');
const link = document.getElementById('download');
const bar = document.getElementById('bar');
const sizeHint = document.getElementById('sizeHint');
const uploadBtn = document.getElementById('uploadBtn');
const countdown = document.getElementById('countdown');
/* ===== Helpers ===== */
function setStatus(s) { statusEl.textContent = s; }
function setSr() { srEl.textContent = 'SampleRate: ' + sampleRate + ' Hz'; }
function currentUserID() { const raw = (document.getElementById('userID').value || '').trim().toUpperCase(); return /^[A-Z][0-9]{3}$/.test(raw) ? raw : 'U000'; }
function currentGender() { const sel = document.querySelector('input[name="gender"]:checked'); const v = sel ? sel.value : 'X'; return (v === 'M' || v === 'F') ? v : 'X'; }
function currentAge2() { const n = parseInt((document.getElementById('age').value || '').trim(), 10); if (isNaN(n) || n<0 || n>120) return '00'; return String(n).padStart(2,'0'); }
function pad2(n){ return String(n).padStart(2,'0'); }
function startMeter(analyser){
function tick(){
const data = new Uint8Array(analyser.fftSize);
analyser.getByteTimeDomainData(data);
let sum = 0;
for (let i=0;i<data.length;i++){ const v=(data[i]-128)/128; sum += v*v; }
const rms = Math.sqrt(sum/data.length);
bar.style.width = Math.min(100, Math.round(rms*200)) + '%';
meterRAF = requestAnimationFrame(tick);
}
tick();
}
function stopMeter(){ if (meterRAF) cancelAnimationFrame(meterRAF); }
function concatFloat32(buffers){
const len = buffers.reduce((a,b)=>a+b.length,0);
const out = new Float32Array(len);
let off = 0; for (const b of buffers){ out.set(b,off); off += b.length; }
return out;
}
function interleaveStereo(left, right){
const N = Math.min(left.length, right.length);
const out = new Float32Array(N * 2);
let j = 0;
for (let i=0;i<N;i++){ out[j++] = left[i]; out[j++] = right[i]; }
return out;
}
function floatTo16BitPCM(float32){
const out = new DataView(new ArrayBuffer(float32.length * 2));
let o = 0;
for (let i=0;i<float32.length;i++,o+=2){
let s = Math.max(-1, Math.min(1, float32[i]));
out.setInt16(o, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
return out;
}
function writeWavHeader(view, sr, numFrames, numChannels = 2, bitsPerSample = 16){
function w(v,o,s){ for(let i=0;i<s.length;i++) v.setUint8(o+i, s.charCodeAt(i)); }
const blockAlign = numChannels * bitsPerSample / 8;
const byteRate = sr * blockAlign;
const dataSize = numFrames * blockAlign;
w(view, 0, 'RIFF'); view.setUint32(4, 36 + dataSize, true);
w(view, 8, 'WAVE');
w(view,12, 'fmt '); view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, sr, true);
view.setUint32(28, byteRate, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitsPerSample, true);
w(view,36, 'data'); view.setUint32(40, dataSize, true);
}
function encodeWavStereo(leftBuffers, rightBuffers, sr){
const left = concatFloat32(leftBuffers);
const right = concatFloat32(rightBuffers.length ? rightBuffers : [left]); // duplicate if mono
const inter = interleaveStereo(left, right);
const pcm16 = floatTo16BitPCM(inter);
const header = new DataView(new ArrayBuffer(44));
writeWavHeader(header, sr, inter.length / 2, 2, 16);
const wav = new Uint8Array(44 + pcm16.byteLength);
wav.set(new Uint8Array(header.buffer), 0);
wav.set(new Uint8Array(pcm16.buffer), 44);
return new Blob([wav], { type: 'audio/wav' });
}
function updateCountdown(){
if (!recording){ countdown.textContent = MAX_SECONDS.toFixed(1) + 's'; return; }
const elapsed = (performance.now() - startTs) / 1000;
const left = Math.max(0, MAX_SECONDS - elapsed);
countdown.textContent = left.toFixed(1) + 's';
countdownRAF = requestAnimationFrame(updateCountdown);
}
async function setupAudio(){
const AC = window.AudioContext || window.webkitAudioContext;
audioCtx = new AC(); sampleRate = audioCtx.sampleRate; setSr();
stream = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 2, echoCancellation:false, noiseSuppression:false, autoGainControl:false }
});
const src = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
src.connect(analyser);
startMeter(analyser);
leftBuffers = []; rightBuffers = [];
if (audioCtx.audioWorklet) {
try {
await audioCtx.audioWorklet.addModule('recorder-worklet.js');
const node = new AudioWorkletNode(audioCtx, 'wav-recorder-processor', { numberOfInputs:1, numberOfOutputs:0, channelCount:2 });
src.connect(node);
node.port.onmessage = (e) => {
if (!recording) return;
if (e.data && e.data.type === 'chunk') {
leftBuffers.push(new Float32Array(e.data.left));
rightBuffers.push(new Float32Array(e.data.right));
const secs = (leftBuffers.reduce((a,b)=>a+b.length,0) / sampleRate);
sizeHint.textContent = 'Length: ' + secs.toFixed(1) + ' s';
}
};
return;
} catch (e) { console.warn('AudioWorklet failed, falling back to ScriptProcessor:', e); }
}
const sp = audioCtx.createScriptProcessor(4096, 2, 0);
src.connect(sp); sp.connect(audioCtx.destination);
sp.onaudioprocess = (ev) => {
if (!recording) return;
const inBuf = ev.inputBuffer;
const chs = inBuf.numberOfChannels || 1;
const L = inBuf.getChannelData(0);
const R = chs > 1 ? inBuf.getChannelData(1) : L;
leftBuffers.push(new Float32Array(L));
rightBuffers.push(new Float32Array(R));
const secs = (leftBuffers.reduce((a,b)=>a+b.length,0) / sampleRate);
sizeHint.textContent = 'Length: ' + secs.toFixed(1) + ' s';
};
}
function buildFilename(){
const user = currentUserID(), g = currentGender(), age = currentAge2();
const d = new Date();
const dd = pad2(d.getDate()), mm = pad2(d.getMonth()+1), yyyy = d.getFullYear();
const hh = pad2(d.getHours()), mi = pad2(d.getMinutes()), ss = pad2(d.getSeconds());
return `${user}_${g}_${age}_audio_${dd}_${mm}_${yyyy}_${hh}_${mi}_${ss}.wav`;
}
async function setPlayerSource(url){
try { player.pause(); } catch {}
player.removeAttribute('src'); player.load();
player.srcObject = null;
if (url) {
player.src = url;
player.load();
try { await player.play(); } catch {}
previewBtn.disabled = false;
} else {
previewBtn.disabled = true;
}
}
function finalizeRecording(){
setStatus('encoding…');
if (stream) stream.getTracks().forEach(t=>t.stop());
stopMeter();
const blob = encodeWavStereo(leftBuffers, rightBuffers, sampleRate);
const url = URL.createObjectURL(blob);
setPlayerSource(url);
const filename = buildFilename();
link.href = url; link.download = filename;
sizeHint.textContent = 'Size: ' + (blob.size/1024/1024).toFixed(2) + ' MB';
setStatus('ready');
recordBtn.disabled = false; recordBtn.textContent = 'Start recording';
resetBtn.disabled = false; uploadBtn.disabled = false;
window.__latestBlob = blob; window.__latestFilename = filename;
}
function startRecording(){
recording = true;
leftBuffers = []; rightBuffers = [];
startTs = performance.now();
updateCountdown();
setStatus('recording…');
recordBtn.textContent = 'Stop recording';
recordBtn.disabled = false;
resetBtn.disabled = false;
uploadBtn.disabled = true;
setPlayerSource('');
stopTimer = setTimeout(()=>{ if(recording) stopRecording(); }, Math.ceil(MAX_SECONDS*1000));
}
function stopRecording(){
if (!recording) return;
recording = false;
if (stopTimer){ clearTimeout(stopTimer); stopTimer = null; }
if (countdownRAF) cancelAnimationFrame(countdownRAF);
countdown.textContent = MAX_SECONDS.toFixed(1) + 's';
finalizeRecording();
}
/* ===== Events ===== */
recordBtn.addEventListener('click', async () => {
try{
if (!recording){
recordBtn.disabled = true;
await setupAudio();
if (audioCtx.state === 'suspended') await audioCtx.resume();
startRecording();
} else {
stopRecording();
}
} catch (e){
console.error(e);
setStatus('permission denied or unavailable');
alert('Microphone access failed. Check browser permissions and HTTPS.');
recordBtn.disabled = false; recordBtn.textContent = 'Start recording'; resetBtn.disabled = true;
}
});
resetBtn.addEventListener('click', () => {
// Reload the page (same as pressing F5). Uses cache like a normal refresh.
window.location.reload();
});
document.getElementById('previewBtn').addEventListener('click', async () => {
try { await player.play(); } catch { alert('Press Play on the audio bar to listen.'); }
});
player.addEventListener('error', () => {
const err = player.error;
if (!err) return;
const map = {1:'MEDIA_ERR_ABORTED',2:'MEDIA_ERR_NETWORK',3:'MEDIA_ERR_DECODE',4:'MEDIA_ERR_SRC_NOT_SUPPORTED'};
alert('Playback error: ' + (map[err.code] || 'UNKNOWN'));
});
async function blobToBase64(blob){
const buf = await blob.arrayBuffer();
let binary = ''; const bytes = new Uint8Array(buf); const chunk = 0x8000;
for (let i=0; i<bytes.length; i+=chunk){
binary += String.fromCharCode.apply(null, bytes.subarray(i, i+chunk));
}
return btoa(binary);
}
// Upload (Safari-friendly: text/plain avoids preflight; fine on Chrome)
uploadBtn.addEventListener('click', async () => {
try{
if (!WEB_APP_URL || WEB_APP_URL.includes('PASTE_')){ alert('Website not configured: missing Apps Script URL.'); return; }
if (!window.__latestBlob){ alert('Record something first.'); return; }
uploadBtn.disabled = true;
const original = uploadBtn.textContent;
uploadBtn.textContent = 'Uploading…';
const base64 = await blobToBase64(window.__latestBlob);
const filename = window.__latestFilename || buildFilename();
const res = await fetch(WEB_APP_URL, {
method: 'POST',
headers: { 'Content-Type': 'text/plain;charset=utf-8' },
body: JSON.stringify({ filename, mimeType: 'audio/wav', data: base64 }),
redirect: 'follow'
});
const raw = await res.text(); let data = null; try { data = JSON.parse(raw); } catch(_){}
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}\n${raw}`);
if (!data || data.ok !== true) throw new Error(data && data.error ? data.error : `Unexpected response: ${raw}`);
alert('Uploaded ✓\n' + (data.finalName || filename));
} catch (e){
console.error('Upload failed:', e);
alert('Upload failed:\n' + e.message);
} finally {
uploadBtn.textContent = 'Upload';
uploadBtn.disabled = false;
}
});
</script>
</body>
</html>