File size: 20,534 Bytes
edbbc3c 4695ac2 edbbc3c 0b3fb1f edbbc3c 0b3fb1f edbbc3c 4fcb7f8 edbbc3c 4fcb7f8 edbbc3c 4fcb7f8 edbbc3c c49e455 edbbc3c ae8fb92 edbbc3c 453d218 edbbc3c ae8fb92 451d768 edbbc3c c805717 edbbc3c c805717 ae8fb92 c805717 ae8fb92 c805717 edbbc3c ae8fb92 edbbc3c c805717 edbbc3c ae8fb92 edbbc3c ae8fb92 df9a855 edbbc3c 4472515 c805717 4472515 edbbc3c cb4abde 502b85f edbbc3c 4472515 0b77764 edbbc3c 0b3fb1f df9a855 f9eec85 b338865 f9eec85 7496426 c805717 24a731a 5e37267 ae8fb92 5e37267 ae8fb92 4fcb7f8 5e37267 edbbc3c 4fcb7f8 edbbc3c ae8fb92 | 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | /* ============================================================
SoundCloud-Style Audio Recorder + Waveform Display + Analyzer
============================================================
*/
// Global variables
let audioContext;
let gumStream;
let rec;
let input;
// DOM Elements
const recordBtn = document.getElementById("recordButton");
const stopBtn = document.getElementById("stopButton");
const pauseBtn = document.getElementById("pauseButton");
const recordingsList = document.getElementById("recordingsList");
const uploadButton = document.getElementById("upload-button");
const uploadInput = document.getElementById("audio-file");
const responseBox = document.getElementById("response");
const metadataBox = document.getElementById("metadata-display");
// ==============================
// Recording Controls
// ==============================
recordBtn.addEventListener("click", startRecording);
stopBtn.addEventListener("click", stopRecording);
pauseBtn.addEventListener("click", pauseRecording);
// Start recording
function startRecording() {
console.log("Recording started...");
recordBtn.disabled = true;
stopBtn.disabled = false;
pauseBtn.disabled = false;
navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
document.getElementById("formats").innerText =
"Sample rate: " + audioContext.sampleRate + " Hz";
gumStream = stream;
input = audioContext.createMediaStreamSource(stream);
rec = new Recorder(input, { numChannels: 1 });
rec.record();
}).catch(function (e) {
console.error("Could not start recording:", e);
recordBtn.disabled = false;
stopBtn.disabled = true;
pauseBtn.disabled = true;
});
}
// Pause recording
function pauseRecording() {
if (rec.recording) {
rec.stop();
pauseBtn.innerText = "Resume";
} else {
rec.record();
pauseBtn.innerText = "Pause";
}
}
// Stop recording
function stopRecording() {
console.log("Recording stopped.");
stopBtn.disabled = true;
recordBtn.disabled = false;
pauseBtn.disabled = true;
pauseBtn.innerText = "Pause";
rec.stop();
gumStream.getAudioTracks()[0].stop();
rec.exportWAV(createWaveformItem);
}
// ==============================
// File Upload
// ==============================
uploadButton.addEventListener("click", () => {
if (!uploadInput.files.length) {
alert("Select at least one file.");
return;
}
Array.from(uploadInput.files).forEach((file) => handleUploadedFile(file));
});
function handleUploadedFile(file) {
const url = URL.createObjectURL(file);
createWaveformItem(file, url);
}
// ==============================
// Create SoundCloud-like Waveform
// ==============================
function createWaveformItem(blob, forcedUrl = null) {
const url = forcedUrl || URL.createObjectURL(blob);
const li = document.createElement("li");
li.className = "wave-item";
const container = document.createElement("div");
container.className = "wave-canvas";
// Waveform and its temporal analysis share one column, so both use the same time axis
const waveCol = document.createElement("div");
waveCol.className = "wave-col";
const timelineEl = document.createElement("div");
timelineEl.className = "timeline";
waveCol.appendChild(container);
waveCol.appendChild(timelineEl);
const meta = document.createElement("div");
meta.className = "wave-meta";
meta.innerHTML = `<div class="file-title">${blob.name || "recording.wav"}</div>`;
// Play button
const playBtn = document.createElement("button");
playBtn.className = "btn btn-play btn-sm";
playBtn.innerText = "Play";
// Analyze button
const analyzeBtn = document.createElement("button");
analyzeBtn.className = "btn btn-outline-secondary btn-sm";
analyzeBtn.innerText = "Analyze";
const controls = document.createElement("div");
controls.className = "wave-controls";
controls.appendChild(analyzeBtn);
controls.appendChild(playBtn);
li.appendChild(controls);
li.appendChild(waveCol);
li.appendChild(meta);
recordingsList.appendChild(li);
// Create WaveSurfer
const wavesurfer = WaveSurfer.create({
container,
autoCenter: true,
waveColor: "#bbb",
progressColor: "#ff5500",
cursorColor: "#333",
barWidth: 2,
height: 70,
responsive: true,
});
// Analyze
const item = { blob, wavesurfer, timelineEl, abort: null, timeline: null };
analyzeBtn.addEventListener("click", () => {
analyzeAudio(item);
});
// Toggle play/pause
playBtn.addEventListener("click", () => {
wavesurfer.playPause();
playBtn.innerText = wavesurfer.isPlaying() ? "Pause" : "Play";
});
wavesurfer.on("finish", () => { playBtn.innerText = "Play"; });
// Keep the timeline's playback cursor in sync with the audio
const syncCursor = () => item.timeline && item.timeline.setCursor(wavesurfer.getCurrentTime());
wavesurfer.on("audioprocess", syncCursor);
wavesurfer.on("seek", syncCursor);
wavesurfer.load(url);
// Metadata
if (metadataBox) blob.arrayBuffer().then((buffer) => {
const ctx = new AudioContext();
ctx.decodeAudioData(buffer).then((decoded) => {
metadataBox.innerHTML = `
<strong>Channels:</strong> ${decoded.numberOfChannels}<br>
<strong>Duration:</strong> ${decoded.duration.toFixed(2)}s<br>
<strong>Sample Rate:</strong> ${decoded.sampleRate} Hz
`;
});
});
}
// ==============================
// Audio Analysis API (placeholder)
// ==============================
async function analyzeAudio(item) {
const blob = item.blob;
// Check if the response element exists
const responseBox = document.getElementById('response');
if (!responseBox) return;
responseBox.innerHTML = "<em>Analyzing...</em>";
// Convert Blob to File
const file = new File([blob], blob.name || "recording.wav", { type: blob.type });
const formData = new FormData();
formData.append("files", file);
try {
// Replace the URL with your real backend endpoint
const res = await fetch("/predict/", {
method: "POST",
body: formData,
});
const data = await res.json();
let message = "Prediction Failed!";
if (data[0]?.status === "success") {
const item = data[0];
const confidencePercent = Math.round(item.confidence * 100);
message = `${item.filename} is ${item.label} with confidence of ${confidencePercent}%`;
}
let messageVolume = "... ";
if (data[0]?.volume === "silent") {
messageVolume = "The audio appears to be silent or contains no detectable speech. Please record/select another file! ";
message = ""
}
if (data[0]?.volume === "augmented") {
messageVolume = "The detected speech volume was low, so a volume augmentation was applied before analysis. ";
}
const volumeColor = "orange";
let predictionColor = message.includes("Genuine") ? "green" : "red";
const silent = data[0]?.volume === "silent";
responseBox.innerHTML = `
<div style="font-size: 1.1rem; margin-bottom: 6px; color:${volumeColor};">
${messageVolume}
</div>
<div style="font-size: 1.25rem; font-weight:600; color:${predictionColor};">
${message}
</div>
`;
// Temporal analysis runs after the global score (one CPU-heavy job at a time)
if (data[0]?.status === "success" && !silent) {
runTimeline(item, file);
}
} catch (err) {
responseBox.innerHTML = `<div style="font-size: 1.25rem; font-weight:600; color:red;">/!\ Analysis failed.</div>`;
console.error(err);
}
}
// ==============================
// Temporal Analysis (sliding window)
// ==============================
const SVG_NS = "http://www.w3.org/2000/svg";
const TL = {
height: 150,
padTop: 10,
padBottom: 22, // room for the time axis labels
ink: "#2b3a55", // the P(genuine) line
genuineTint: "rgba(12, 163, 12, 0.08)",
spoofTint: "rgba(208, 59, 59, 0.08)",
grid: "#e6e6e6",
cursor: "#ff5500", // same orange as the waveform progress
};
function svgEl(tag, attrs = {}, parent = null) {
const el = document.createElementNS(SVG_NS, tag);
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
if (parent) parent.appendChild(el);
return el;
}
const fmtPct = (p) => `${(p * 100).toFixed(1)}%`;
const fmtSec = (t) => `${t.toFixed(t < 10 ? 2 : 1)} s`;
function niceTimeStep(duration, widthPx) {
const maxTicks = Math.max(2, Math.floor(widthPx / 60));
const steps = [0.25, 0.5, 1, 2, 5, 10, 15, 30, 60, 120];
return steps.find((s) => duration / s <= maxTicks) || 300;
}
// Read an NDJSON stream line by line
async function* readNdjson(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let nl;
while ((nl = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (line) yield JSON.parse(line);
}
}
if (buffer.trim()) yield JSON.parse(buffer);
}
async function runTimeline(item, file) {
// A new analysis of the same item replaces the running one
if (item.abort) item.abort.abort();
item.abort = new AbortController();
const windowSec = document.getElementById("tl-window")?.value || "4";
const hopSec = document.getElementById("tl-hop")?.value || "1";
const chart = createTimelineChart(item);
item.timeline = chart;
chart.setStatus("Temporal analysis: uploading…");
const formData = new FormData();
formData.append("file", file);
formData.append("window_sec", windowSec);
formData.append("hop_sec", hopSec);
try {
const res = await fetch("/timeline/", {
method: "POST",
body: formData,
signal: item.abort.signal,
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.detail || `HTTP ${res.status}`);
}
for await (const msg of readNdjson(res)) {
if (msg.n_windows !== undefined) chart.setHeader(msg);
else chart.addSegment(msg);
}
chart.finish();
} catch (err) {
if (err.name === "AbortError") return;
console.error(err);
chart.setStatus(`Temporal analysis failed: ${err.message}`);
}
}
function createTimelineChart(item) {
const root = item.timelineEl;
root.replaceChildren();
root.classList.add("active");
const status = document.createElement("div");
status.className = "timeline-status";
const plot = document.createElement("div");
plot.className = "timeline-plot";
const svg = svgEl("svg", { height: TL.height, role: "img" }, plot);
const tip = document.createElement("div");
tip.className = "timeline-tip";
plot.appendChild(tip);
// Table view: the same numbers without hovering
const details = document.createElement("details");
const summary = document.createElement("summary");
summary.textContent = "Segment values";
const table = document.createElement("table");
const thead = table.createTHead().insertRow();
["Start", "End", "P(genuine)", "Decision"].forEach((h) => {
const th = document.createElement("th");
th.textContent = h;
thead.appendChild(th);
});
const tbody = table.createTBody();
details.append(summary, table);
root.append(status, plot, details);
const state = { header: null, segments: [], cursor: null, hover: null, done: false };
const duration = () => {
const d = item.wavesurfer.getDuration();
return d > 0 ? d : state.header?.duration || 1;
};
const geom = () => {
const w = plot.clientWidth || 600;
const h = TL.height;
const y0 = TL.padTop, y1 = h - TL.padBottom;
return {
w, h, y0, y1,
x: (t) => (t / duration()) * w,
y: (p) => y1 - p * (y1 - y0),
t: (px) => Math.min(Math.max(px / w, 0), 1) * duration(),
};
};
const center = (s) => (s.start + s.end) / 2;
function render() {
const g = geom();
svg.replaceChildren();
svg.setAttribute("viewBox", `0 0 ${g.w} ${g.h}`);
// Zones: above 50% = genuine, below = spoof
svgEl("rect", { x: 0, y: g.y0, width: g.w, height: g.y(0.5) - g.y0, fill: TL.genuineTint }, svg);
svgEl("rect", { x: 0, y: g.y(0.5), width: g.w, height: g.y1 - g.y(0.5), fill: TL.spoofTint }, svg);
// Hovered window span
if (state.hover !== null) {
const s = state.segments[state.hover];
svgEl("rect", {
x: g.x(s.start), y: g.y0, width: Math.max(1, g.x(s.end) - g.x(s.start)),
height: g.y1 - g.y0, fill: "rgba(43, 58, 85, 0.07)",
}, svg);
}
// Grid at 0 / 50 / 100 %, decision threshold dashed
[0, 0.5, 1].forEach((p) => {
svgEl("line", {
x1: 0, x2: g.w, y1: g.y(p), y2: g.y(p),
stroke: p === 0.5 ? "#9aa0a6" : TL.grid,
"stroke-width": 1, "stroke-dasharray": p === 0.5 ? "4 3" : "",
}, svg);
});
const ylab = (txt, p, dy) => {
const t = svgEl("text", { x: g.w - 4, y: g.y(p) + dy, "text-anchor": "end" }, svg);
t.textContent = txt;
};
ylab("100%", 1, 11);
ylab("50%", 0.5, -4);
ylab("0%", 0, -4);
const zlab = (txt, y) => {
const t = svgEl("text", { x: 4, y, "font-weight": 600 }, svg);
t.textContent = txt;
};
zlab("▲ Genuine", g.y0 + 12);
zlab("▼ Spoof", g.y1 - 5);
// Time axis
const step = niceTimeStep(duration(), g.w);
for (let t = 0; t <= duration() + 1e-9; t += step) {
const x = g.x(t);
svgEl("line", { x1: x, x2: x, y1: g.y1, y2: g.y1 + 4, stroke: "#bbb" }, svg);
const lbl = svgEl("text", {
x, y: g.h - 6,
"text-anchor": t === 0 ? "start" : x > g.w - 20 ? "end" : "middle",
}, svg);
lbl.textContent = `${+t.toFixed(2)}s`;
}
// P(genuine) line through window centres; silent windows break the line
let d = "";
let pen = false;
state.segments.forEach((s) => {
if (s.silent) { pen = false; return; }
d += `${pen ? "L" : "M"}${g.x(center(s)).toFixed(1)},${g.y(s.bonafide_prob).toFixed(1)}`;
pen = true;
});
if (d) {
svgEl("path", {
d, fill: "none", stroke: TL.ink, "stroke-width": 2,
"stroke-linejoin": "round", "stroke-linecap": "round",
}, svg);
}
// Markers (only when sparse enough to stay readable)
const showDots = state.segments.length <= 60;
state.segments.forEach((s, i) => {
const cx = g.x(center(s));
if (s.silent) {
svgEl("line", {
x1: cx - 4, x2: cx + 4, y1: g.y1 - 3, y2: g.y1 - 3,
stroke: "#adb5bd", "stroke-width": 2, "stroke-linecap": "round",
}, svg);
return;
}
if (!showDots && i !== state.hover) return;
svgEl("circle", {
cx, cy: g.y(s.bonafide_prob), r: i === state.hover ? 5 : 3.5,
fill: TL.ink, stroke: "#fff", "stroke-width": 2,
}, svg);
});
// Crosshair on hover
if (state.hover !== null) {
const x = g.x(center(state.segments[state.hover]));
svgEl("line", { x1: x, x2: x, y1: g.y0, y2: g.y1, stroke: TL.ink, "stroke-width": 1, opacity: 0.4 }, svg);
}
// Playback cursor
if (state.cursor !== null) {
const x = g.x(state.cursor);
svgEl("line", { x1: x, x2: x, y1: 0, y2: g.y1, stroke: TL.cursor, "stroke-width": 2 }, svg);
}
svg.setAttribute("aria-label", ariaSummary());
}
function ariaSummary() {
const scored = state.segments.filter((s) => !s.silent);
if (!scored.length) return "Temporal analysis: no scored segments yet";
const spoofed = scored.filter((s) => s.bonafide_prob < 0.5).length;
return `Probability of genuine speech over time: ${spoofed} of ${scored.length} segments below 50%`;
}
function updateStatus() {
const h = state.header;
if (!h) return;
const n = state.segments.length;
const cfg = `window ${h.window_sec} s · hop ${h.hop_sec} s`;
status.replaceChildren();
const strong = document.createElement("strong");
if (!state.done) {
strong.textContent = `Temporal analysis: ${n} / ${h.n_windows} segments`;
status.append(strong, ` · ${cfg} · computing…`);
return;
}
const scored = state.segments.filter((s) => !s.silent);
const spoofed = scored.filter((s) => s.bonafide_prob < 0.5).length;
const silent = n - scored.length;
strong.textContent = `${spoofed} of ${scored.length} segments look spoofed`;
status.append(
strong,
` · ${cfg}${silent ? ` · ${silent} silent segment${silent > 1 ? "s" : ""} not scored` : ""}`,
);
}
function addRow(s) {
const row = tbody.insertRow();
[
fmtSec(s.start),
fmtSec(s.end),
s.silent ? "—" : fmtPct(s.bonafide_prob),
s.silent ? "silent" : s.bonafide_prob >= 0.5 ? "Genuine" : "Spoof",
].forEach((v) => { row.insertCell().textContent = v; });
}
// Hover: snap to the nearest window centre
function showTip(i) {
const s = state.segments[i];
const g = geom();
tip.replaceChildren();
const value = document.createElement("div");
value.className = "tip-value";
value.textContent = s.silent ? "silent" : `${fmtPct(s.bonafide_prob)} genuine`;
const label = document.createElement("div");
label.className = "tip-label";
label.textContent = `${fmtSec(s.start)} – ${fmtSec(s.end)}`
+ (s.silent ? " · not scored" : ` · ${s.bonafide_prob >= 0.5 ? "Genuine" : "Spoof"}`);
tip.append(value, label);
tip.style.display = "block";
const x = g.x(center(s));
const tw = tip.offsetWidth;
tip.style.left = `${Math.min(Math.max(x - tw / 2, 0), g.w - tw)}px`;
tip.style.top = `${Math.max(0, (s.silent ? g.y1 : g.y(s.bonafide_prob)) - tip.offsetHeight - 10)}px`;
}
svg.addEventListener("pointermove", (e) => {
if (!state.segments.length) return;
const t = geom().t(e.offsetX);
let best = 0;
state.segments.forEach((s, i) => {
if (Math.abs(center(s) - t) < Math.abs(center(state.segments[best]) - t)) best = i;
});
if (best !== state.hover) {
state.hover = best;
render();
}
showTip(best);
});
svg.addEventListener("pointerleave", () => {
state.hover = null;
tip.style.display = "none";
render();
});
// Click to play from that point
svg.addEventListener("click", (e) => {
const g = geom();
item.wavesurfer.seekTo(g.t(e.offsetX) / duration());
});
new ResizeObserver(() => render()).observe(plot);
render();
return {
setStatus(text) { status.textContent = text; },
setHeader(h) { state.header = h; updateStatus(); render(); },
addSegment(s) { state.segments.push(s); addRow(s); updateStatus(); render(); },
finish() { state.done = true; updateStatus(); render(); },
setCursor(t) { state.cursor = t; render(); },
};
}
|