Spaces:
Paused

assistant / ui /web /src /lib /audio.js
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
8.19 kB
// Browser-side audio helpers for the STT tab (record / trim / save).
//
// Everything here is a pure function over the Web Audio API β€” no DOM, no
// external library. The two transformations that matter:
//
// 1. Recordings come out of MediaRecorder as webm/opus, which the Python
// STT backends (soundfile, whisper-server) can NOT read. We decode the
// blob and re-encode it as 16-bit PCM WAV β€” the one format every
// consumer is guaranteed to read.
// 2. Trimming cuts an AudioBuffer between two timestamps and re-encodes
// the slice to WAV, which doubles as the "preview" of the cut.
let _ctx = null;
/** The shared AudioContext β€” created lazily (browsers cap the number of
* live contexts and it may only be created after a user gesture). */
function ctx() {
if (!_ctx) _ctx = new (window.AudioContext || window.webkitAudioContext)();
return _ctx;
}
/** Decode a File/Blob to a PCM AudioBuffer. Chrome decodes webm/opus,
* wav, mp3, ogg and m4a here, so this works for uploads AND recordings. */
export async function decodeAudioFile(file) {
const buf = await file.arrayBuffer();
return ctx().decodeAudioData(buf);
}
/** Cut `buffer` between startSec and endSec (clamped to the buffer's
* bounds; invalid ranges collapse to a 1-sample minimum). Returns a NEW
* AudioBuffer at the same sample rate β€” the source is never mutated. */
export function sliceBuffer(buffer, startSec, endSec) {
const sr = buffer.sampleRate;
const start = Math.max(0, Math.min(buffer.duration, startSec));
const end = Math.max(start, Math.min(buffer.duration, endSec));
const length = Math.max(1, Math.round((end - start) * sr));
const out = ctx().createBuffer(buffer.numberOfChannels, length, sr);
const off = Math.round(start * sr);
for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
const src = buffer.getChannelData(ch);
const dst = out.getChannelData(ch);
for (let i = 0; i < length; i++) dst[i] = src[off + i] || 0;
}
return out;
}
/** Encode an AudioBuffer as a 16-bit PCM mono/stereo WAV Blob (44-byte
* RIFF header + interleaved samples). */
export function bufferToWav(buffer) {
const numCh = buffer.numberOfChannels;
const sr = buffer.sampleRate;
const len = buffer.length;
const blockAlign = numCh * 2;
const dataSize = len * blockAlign;
const ab = new ArrayBuffer(44 + dataSize);
const view = new DataView(ab);
writeStr(view, 0, "RIFF");
view.setUint32(4, 36 + dataSize, true);
writeStr(view, 8, "WAVE");
writeStr(view, 12, "fmt ");
view.setUint32(16, 16, true); // fmt chunk size
view.setUint16(20, 1, true); // PCM
view.setUint16(22, numCh, true);
view.setUint32(24, sr, true);
view.setUint32(28, sr * blockAlign, true); // byte rate
view.setUint16(32, blockAlign, true);
view.setUint16(34, 16, true); // bits per sample
writeStr(view, 36, "data");
view.setUint32(40, dataSize, true);
const channels = [];
for (let ch = 0; ch < numCh; ch++) channels.push(buffer.getChannelData(ch));
let offset = 44;
for (let i = 0; i < len; i++) {
for (let ch = 0; ch < numCh; ch++) {
let s = channels[ch][i];
s = Math.max(-1, Math.min(1, s));
// 16-bit PCM: negative β†’ 0x8000 range, positive β†’ 0x7FFF range.
view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
offset += 2;
}
}
return new Blob([ab], { type: "audio/wav" });
}
/** Seconds β†’ "m:ss" (or "0:00" for junk input). */
export function formatDuration(sec) {
if (!isFinite(sec) || sec < 0) return "0:00";
const m = Math.floor(sec / 60);
const s = Math.round(sec % 60);
return `${m}:${String(s).padStart(2, "0")}`;
}
/** Draw a peak-envelope waveform of `buffer` onto `canvas` β€” the
* before/after comparison in the STT tab's noise-reduction preview AND the
* STT trim bar's selection view. Uses channel 0, collapses every pixel
* column to its min/max peak so quiet passages stay visible, and renders
* crisp on HiDPI screens. `color` is a CSS color string; width follows the
* canvas's current layout width.
*
* `selection` ({start, end} in seconds, e.g. the trim sliders' kept region)
* colors that span in `selectColor` and draws thin handle lines at its
* boundaries, so the exact cut points are visible on the audio shape.
* `playhead` (seconds, e.g. the audio element's currentTime) draws a thin
* line at the live playback position on top of everything.
*
* Returns the canvas for chaining. Never throws on a bad buffer β€” a null
* buffer just clears the canvas. */
export function drawWaveform(
canvas,
buffer,
{
color = "#8a7a68",
selection = null,
selectColor = "#d97757",
playhead = null,
playheadColor = "#4e7a57",
} = {}
) {
// Canvas fillStyle does NOT resolve CSS custom properties (var(--x)) β€” the
// color must be a concrete value. Resolve a var()/fallback string here so
// callers can pass theme tokens and still get a real color (falls back to
// the token's own fallback, then to a neutral grey).
color = resolveColor(color);
selectColor = resolveColor(selectColor);
const g = canvas.getContext("2d");
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth || canvas.parentElement?.clientWidth || 300;
const h = 64;
canvas.width = Math.max(1, Math.round(w * dpr));
canvas.height = Math.round(h * dpr);
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, w, h);
if (!buffer) return canvas;
const data = buffer.getChannelData(0);
const cols = Math.max(1, Math.floor(w));
const per = Math.max(1, Math.floor(data.length / cols));
const mid = h / 2;
// Map the selection span (seconds) onto the column range, clamped so a
// sliver at the very edge can't draw outside the canvas.
let selStartCol = -1;
let selEndCol = -1;
if (selection && buffer.duration > 0) {
selStartCol = Math.max(0, Math.floor((selection.start / buffer.duration) * cols));
selEndCol = Math.min(cols, Math.ceil((selection.end / buffer.duration) * cols));
}
for (let c = 0; c < cols; c++) {
let mn = 1;
let mx = -1;
const start = c * per;
const end = Math.min(data.length, start + per);
for (let i = start; i < end; i++) {
const v = data[i];
if (v < mn) mn = v;
if (v > mx) mx = v;
}
const top = Math.max(0, mid - mx * (mid - 2));
const bot = Math.min(h, mid - mn * (mid - 2));
if (bot > top) {
// Columns inside the kept span render in the highlight color, the
// trimmed-away parts stay in the dim base color.
g.fillStyle = c >= selStartCol && c < selEndCol ? selectColor : color;
g.fillRect(c, top, 1, bot - top);
}
}
// Handle lines marking the exact trim start/end columns (drawn in the
// theme's strong text color so they read on both light and dark).
if (selection && selStartCol >= 0 && selEndCol > selStartCol) {
g.fillStyle = resolveColor("var(--text-strong, #3f332b)");
g.fillRect(selStartCol, 0, 2, h);
g.fillRect(selEndCol - 2, 0, 2, h);
}
// Live playback position line (the audio player's currentTime), drawn on
// top so the playhead stays visible over the selection highlight.
if (playhead != null && buffer.duration > 0) {
const col = Math.floor((playhead / buffer.duration) * cols);
if (col >= 0 && col < cols) {
g.fillStyle = resolveColor(playheadColor);
g.fillRect(col, 0, 2, h);
}
}
return canvas;
}
function writeStr(view, offset, str) {
for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
}
/** Resolve a CSS color that may be a `var(--token, fallback)` custom-property
* string to a concrete color value (canvas can't read CSS vars itself).
* Unknown tokens fall back through: token fallback β†’ neutral grey. */
function resolveColor(color) {
if (typeof color !== "string" || !color.startsWith("var(")) return color;
const m = /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)/.exec(color);
if (!m) return color;
let resolved = "";
try {
resolved = getComputedStyle(document.documentElement)
.getPropertyValue(m[1])
.trim();
} catch {
resolved = "";
}
return resolved || (m[2] ? m[2].trim() : "#8a7a68");
}