#141 ui dark mobile: high Media & Timeline

Waveform Audio/Video Clipper

Canvas 2D audio waveform editor with draggable in/out trim handles, scrubbable playhead, named markers, and synced transcript.

Inspired by Descript ↗

Download .html
Fullscreen ↗

WHY THIS AESTHETIC IS UNIQUE

Bridges precision acoustic waveform scrubbing with clickable word-level transcript sync and named chapter markers, giving editors both visual trim handles and touch-friendly controls.

BEST FOR

Podcast and voice-note clip editorsShort-form video highlight trimmersUser-research interview annotation toolsSound design and sample-pack previews

TAGS

COLOR PALETTE (CLICK TO COPY HEX)

TYPOGRAPHY

Display
Inter
Body
Inter
Mono
JetBrains Mono
Scale
22px mono timecode display (00:14.2), 14px transcript sentences, 11px mono clip in/out and duration badges.

Google Fonts Stylesheet ↗

ARCHITECTURE & MOBILE NOTES

LAYOUT

Full-width Canvas 2D waveform stage with transport bar above and a 2-column synced transcript + marker rail below (stacking vertically on mobile).

INTERACTION

Pointer-drag In/Out trim handles to define the clip region, click/drag anywhere on the waveform to scrub, press Space/Play to run the live playhead, and add or jump to named markers.

MOBILE

Expands trim handle touch zones to >=44px, stacks transport controls cleanly, and lets mobile users tap any transcript sentence to jump the playhead.

AI AGENT GUARDRAILS

DO

  • Scale HTML5 Canvas 2D by devicePixelRatio so waveform bars stay razor-sharp on Retina displays.
  • Give draggable In/Out trim handles generous >=44px hit targets for touch accuracy.
  • Display live tabular timecodes for Current Position, Clip In, Clip Out, and Selection Duration.

DON'T

  • Never rely on tiny 4px-wide handles that cannot be grabbed on a touchscreen.
  • Avoid letting the playhead run past the Out trim boundary when Loop Selection is active.
STANDALONE SOURCE · demos/waveform-audio-clipper.html (23.7 KB)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cadence Cut — Waveform Audio Clipper &amp; Marker Timeline</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #0c0e14;
    --panel: #141822;
    --panel-2: #1b202e;
    --border: #272e40;
    --ink: #eef2ff;
    --muted: #8c96b0;
    --coral: #ff6b57;
    --coral-soft: rgba(255, 107, 87, 0.16);
    --cyan: #22d3ee;
    --cyan-soft: rgba(34, 211, 238, 0.14);
    --amber: #fbbf24;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { overflow-x: hidden; }
  body {
    font-family: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif;
    background: var(--bg);
    color: var(--ink);
    min-height: 100vh;
    padding: 16px;
  }
  .mono { font-family: 'JetBrains Mono', ui-monospace, monospace; }

  .studio {
    max-width: 1240px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  header.bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 12px 16px;
  }
  .title-block {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  .rec-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: var(--coral);
    box-shadow: 0 0 12px var(--coral);
    flex-shrink: 0;
  }
  .title-block h1 { font-size: 16.5px; font-weight: 700; }
  .title-block p { font-size: 12px; color: var(--muted); }
  .clip-stats {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
  }
  .stat-pill {
    background: var(--panel-2);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 6px 10px;
    font-size: 12px;
    color: var(--muted);
  }
  .stat-pill strong { color: var(--ink); font-weight: 600; }
  .btn {
    min-height: 44px;
    padding: 0 14px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: var(--panel-2);
    color: var(--ink);
    font: inherit;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    transition: background 0.15s, border-color 0.15s;
  }
  .btn:hover { background: #242b3d; border-color: #3b4661; }
  .btn-coral {
    background: var(--coral);
    border-color: var(--coral);
    color: #0c0e14;
  }
  .btn-coral:hover { background: #ff806f; border-color: #ff806f; }
  .btn-cyan {
    background: var(--cyan-soft);
    border-color: rgba(34, 211, 238, 0.45);
    color: var(--cyan);
  }

  /* Timeline Deck */
  .deck {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  .transport {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }
  .transport-left {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }
  .timecode {
    font-size: 22px;
    font-weight: 600;
    letter-spacing: -0.02em;
    color: var(--cyan);
    padding: 0 8px;
    font-variant-numeric: tabular-nums;
  }
  .timecode small { font-size: 13px; color: var(--muted); font-weight: 400; }
  .transport-right {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }
  .loop-toggle.active {
    background: var(--coral-soft);
    border-color: var(--coral);
    color: var(--coral);
  }

  /* Canvas Waveform Stage */
  .wave-stage {
    position: relative;
    height: 184px;
    background: #0a0c11;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
    touch-action: none;
    user-select: none;
    cursor: crosshair;
  }
  canvas#waveCanvas {
    width: 100%;
    height: 100%;
    display: block;
  }
  .trim-handle {
    position: absolute;
    top: 22px;
    bottom: 0;
    width: 16px;
    margin-left: -8px;
    cursor: ew-resize;
    z-index: 6;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .trim-handle::before {
    content: "";
    width: 4px;
    height: 100%;
    background: var(--coral);
    border-radius: 2px;
  }
  .trim-handle::after {
    content: "";
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 14px;
    height: 36px;
    border-radius: 5px;
    background: var(--coral);
    border: 2px solid #0c0e14;
    box-shadow: 0 2px 10px rgba(255, 107, 87, 0.45);
  }
  .trim-badge {
    position: absolute;
    top: 2px;
    background: var(--coral);
    color: #0c0e14;
    font-size: 10px;
    font-weight: 700;
    padding: 1px 5px;
    border-radius: 4px;
    white-space: nowrap;
  }
  .playhead {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 2px;
    background: var(--cyan);
    z-index: 7;
    pointer-events: none;
    box-shadow: 0 0 8px var(--cyan);
  }
  .playhead::before {
    content: "";
    position: absolute;
    top: 0;
    left: -6px;
    border-left: 7px solid transparent;
    border-right: 7px solid transparent;
    border-top: 10px solid var(--cyan);
  }

  .ruler-hint {
    display: flex;
    justify-content: space-between;
    font-size: 11.5px;
    color: var(--muted);
    flex-wrap: wrap;
    gap: 8px;
  }

  /* Lower split: Synced Transcript + Markers */
  .lower-grid {
    display: grid;
    grid-template-columns: 1.35fr 1fr;
    gap: 14px;
  }
  .card {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  .card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
  }
  .card-head h2 {
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--muted);
  }
  .transcript-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .cue {
    padding: 11px 13px;
    border-radius: 10px;
    border: 1px solid transparent;
    background: var(--panel-2);
    cursor: pointer;
    transition: border-color 0.15s, background 0.15s, opacity 0.15s;
  }
  .cue:hover { border-color: #39445e; }
  .cue.active {
    border-color: var(--cyan);
    background: rgba(34, 211, 238, 0.09);
  }
  .cue.trimmed { opacity: 0.36; }
  .cue-meta {
    display: flex;
    justify-content: space-between;
    font-size: 11.5px;
    color: var(--muted);
    margin-bottom: 4px;
  }
  .cue-speaker { color: var(--coral); font-weight: 600; }
  .cue-text { font-size: 13.5px; line-height: 1.5; color: var(--ink); }

  .marker-form {
    display: flex;
    gap: 8px;
  }
  .marker-form input {
    flex: 1;
    min-width: 0;
    min-height: 44px;
    padding: 0 12px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: #0d1018;
    color: var(--ink);
    font: inherit;
    font-size: 13.5px;
  }
  .marker-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .marker-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 10px;
    background: var(--panel-2);
    border: 1px solid var(--border);
  }
  .marker-jump {
    flex: 1;
    min-height: 36px;
    background: none;
    border: none;
    color: inherit;
    font: inherit;
    text-align: left;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .marker-tag {
    font-size: 11.5px;
    color: var(--amber);
    background: rgba(251, 191, 36, 0.14);
    padding: 3px 7px;
    border-radius: 6px;
    flex-shrink: 0;
  }
  .marker-del {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    border: 1px solid var(--border);
    background: transparent;
    color: var(--muted);
    cursor: pointer;
    font-size: 16px;
  }
  .marker-del:hover { color: var(--coral); border-color: var(--coral); }

  .toast {
    position: fixed;
    bottom: 18px;
    right: 18px;
    background: #182330;
    border: 1px solid var(--cyan);
    color: var(--ink);
    padding: 11px 16px;
    border-radius: 10px;
    font-size: 13px;
    opacity: 0;
    transform: translateY(10px);
    pointer-events: none;
    transition: all 0.2s;
    z-index: 40;
  }
  .toast.show { opacity: 1; transform: translateY(0); }

  @media (max-width: 860px) {
    body { padding: 10px; }
    .lower-grid { grid-template-columns: 1fr; }
    .wave-stage { height: 156px; }
    .timecode { font-size: 18px; }
  }
</style>
</head>
<body>
<div class="studio">
  <header class="bar">
    <div class="title-block">
      <span class="rec-dot"></span>
      <div>
        <h1>EP 42 — Designing Local-First Sync Engines.wav</h1>
        <p>48 kHz · 24-bit Stereo · Host: Maya Lin &amp; Guest: Tomas Novak</p>
      </div>
    </div>
    <div class="clip-stats">
      <div class="stat-pill mono">IN <strong id="statIn">00:08.0</strong></div>
      <div class="stat-pill mono">OUT <strong id="statOut">00:46.5</strong></div>
      <div class="stat-pill mono">CLIP <strong id="statDur">38.5s</strong></div>
      <button class="btn btn-coral" id="exportBtn">Export Clip</button>
    </div>
  </header>

  <section class="deck">
    <div class="transport">
      <div class="transport-left">
        <button class="btn btn-coral" id="playBtn" aria-label="Play or pause">&#9654; Play</button>
        <button class="btn" id="jumpInBtn" title="Jump to In point">To In</button>
        <button class="btn loop-toggle active" id="loopBtn">Loop Clip</button>
        <div class="timecode mono" id="timeDisplay">00:08.0 <small>/ 01:00.0</small></div>
      </div>
      <div class="transport-right">
        <button class="btn btn-cyan" id="setInBtn">Set In [I]</button>
        <button class="btn btn-cyan" id="setOutBtn">Set Out [O]</button>
        <button class="btn" id="quickMarkerBtn">+ Marker [M]</button>
      </div>
    </div>

    <div class="wave-stage" id="waveStage">
      <canvas id="waveCanvas"></canvas>
      <div class="trim-handle" id="handleIn" aria-label="In trim handle"><span class="trim-badge mono">IN</span></div>
      <div class="trim-handle" id="handleOut" aria-label="Out trim handle"><span class="trim-badge mono">OUT</span></div>
      <div class="playhead" id="playhead"></div>
    </div>

    <div class="ruler-hint">
      <span>Click or drag waveform to scrub playhead · Drag coral IN / OUT handles to trim clip</span>
      <span class="mono">Space: Play/Pause · I/O: Trim · M: Drop Marker</span>
    </div>
  </section>

  <div class="lower-grid">
    <section class="card">
      <div class="card-head">
        <h2>Synced Transcript</h2>
        <span style="font-size:12px;color:var(--muted)">Click any line to seek</span>
      </div>
      <div class="transcript-list" id="transcriptList"></div>
    </section>

    <section class="card">
      <div class="card-head">
        <h2>Timeline Markers</h2>
        <span class="mono" style="font-size:12px;color:var(--amber)" id="markerCount">4 markers</span>
      </div>
      <form class="marker-form" id="markerForm">
        <input id="markerInput" type="text" placeholder="Label marker at playhead..." maxlength="48">
        <button type="submit" class="btn btn-cyan">Add</button>
      </form>
      <div class="marker-list" id="markerList"></div>
    </section>
  </div>
</div>

<div class="toast" id="toast" role="status" aria-live="polite"></div>

<script>
(() => {
  const DURATION = 60.0; // 60 seconds
  let inTime = 8.0;
  let outTime = 46.5;
  let currentTime = 8.0;
  let isPlaying = false;
  let loopClip = true;
  let lastFrame = null;

  // Deterministic realistic speech envelope (180 bars)
  const BARS = 180;
  const peaks = Array.from({ length: BARS }, (_, i) => {
    const t = (i / BARS) * DURATION;
    const phrase = Math.sin(t * 0.65) * 0.25 + 0.55;
    const syllable = Math.abs(Math.sin(i * 1.37) * Math.cos(i * 0.53));
    const pause = (t > 16.5 && t < 18.2) || (t > 32.8 && t < 34.1) || (t > 47.0 && t < 48.5) ? 0.14 : 1;
    return Math.max(0.08, Math.min(0.96, (0.18 + syllable * 0.72 * phrase) * pause));
  });

  const TRANSCRIPT = [
    { start: 0, end: 8.0, speaker: 'Maya Lin', text: 'Welcome back to Systems Craft. Before we dive into CRDTs, let us do a quick mic check and intro.' },
    { start: 8.0, end: 17.5, speaker: 'Maya Lin', text: 'The moment users feel zero latency on every keystroke, they stop thinking about whether they are online.' },
    { start: 17.5, end: 27.0, speaker: 'Tomas Novak', text: 'Exactly. We moved the source of truth into IndexedDB and treated the server as a reconciliation peer rather than a gatekeeper.' },
    { start: 27.0, end: 36.5, speaker: 'Maya Lin', text: 'How did you keep conflict resolution legible for designers who do not want to read merge trees?' },
    { start: 36.5, end: 46.5, speaker: 'Tomas Novak', text: 'Every edit carries a hybrid logical clock and a tiny intent tag, so two offline tabs merge cleanly ninety-nine percent of the time.' },
    { start: 46.5, end: 60.0, speaker: 'Maya Lin', text: 'That is a great pull-quote for the teaser reel. Next up, let us unpack compaction and snapshot sizes.' }
  ];

  let markers = [
    { id: 1, time: 8.0, label: 'Hook — Zero Latency Feel' },
    { id: 2, time: 18.4, label: 'IndexedDB as Source of Truth' },
    { id: 3, time: 37.2, label: 'Hybrid Logical Clock Quote' },
    { id: 4, time: 46.5, label: 'Teaser Outro Cut' }
  ];
  let nextMarkerId = 10;

  const waveStage = document.getElementById('waveStage');
  const canvas = document.getElementById('waveCanvas');
  const ctx = canvas.getContext('2d');
  const handleIn = document.getElementById('handleIn');
  const handleOut = document.getElementById('handleOut');
  const playhead = document.getElementById('playhead');
  const playBtn = document.getElementById('playBtn');
  const timeDisplay = document.getElementById('timeDisplay');
  const transcriptList = document.getElementById('transcriptList');
  const markerList = document.getElementById('markerList');

  function fmt(sec) {
    const m = Math.floor(sec / 60);
    const s = Math.floor(sec % 60);
    const d = Math.floor((sec % 1) * 10);
    return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${d}`;
  }

  function showToast(msg) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 2400);
  }

  function drawWave() {
    const rect = waveStage.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    canvas.width = Math.round(rect.width * dpr);
    canvas.height = Math.round(rect.height * dpr);
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    const W = rect.width;
    const H = rect.height;
    const rulerH = 22;
    const midY = rulerH + (H - rulerH) / 2;
    const maxAmp = (H - rulerH) * 0.42;

    ctx.fillStyle = '#0a0c11';
    ctx.fillRect(0, 0, W, H);

    // Ruler background & ticks
    ctx.fillStyle = '#121621';
    ctx.fillRect(0, 0, W, rulerH);
    ctx.strokeStyle = '#272e40';
    ctx.beginPath();
    ctx.moveTo(0, rulerH);
    ctx.lineTo(W, rulerH);
    ctx.stroke();

    ctx.fillStyle = '#7e88a3';
    ctx.font = '10px JetBrains Mono, monospace';
    for (let s = 0; s <= DURATION; s += 5) {
      const x = (s / DURATION) * W;
      ctx.strokeStyle = '#2c3448';
      ctx.beginPath();
      ctx.moveTo(x, rulerH - 6);
      ctx.lineTo(x, rulerH);
      ctx.stroke();
      if (s < DURATION) ctx.fillText(`0:${String(s).padStart(2, '0')}`, x + 4, 14);
    }

    const inX = (inTime / DURATION) * W;
    const outX = (outTime / DURATION) * W;

    // Selected region tint
    ctx.fillStyle = 'rgba(255, 107, 87, 0.08)';
    ctx.fillRect(inX, rulerH, outX - inX, H - rulerH);

    // Center line
    ctx.strokeStyle = '#1c2230';
    ctx.beginPath();
    ctx.moveTo(0, midY);
    ctx.lineTo(W, midY);
    ctx.stroke();

    // Waveform bars
    const step = W / BARS;
    const barW = Math.max(1.5, step * 0.62);
    for (let i = 0; i < BARS; i++) {
      const x = i * step;
      const t = (i / BARS) * DURATION;
      const h = peaks[i] * maxAmp;
      const inRegion = t >= inTime && t <= outTime;
      const played = t <= currentTime;
      if (inRegion) {
        ctx.fillStyle = played ? '#22d3ee' : '#ff6b57';
      } else {
        ctx.fillStyle = '#2b3346';
      }
      ctx.fillRect(x, midY - h, barW, h * 2);
    }

    // Dimmed outside regions
    ctx.fillStyle = 'rgba(10, 12, 17, 0.45)';
    ctx.fillRect(0, rulerH, inX, H - rulerH);
    ctx.fillRect(outX, rulerH, W - outX, H - rulerH);

    // Marker flags on waveform
    markers.forEach(m => {
      const mx = (m.time / DURATION) * W;
      ctx.strokeStyle = '#fbbf24';
      ctx.lineWidth = 1.5;
      ctx.beginPath();
      ctx.moveTo(mx, rulerH);
      ctx.lineTo(mx, H);
      ctx.stroke();
      ctx.fillStyle = '#fbbf24';
      ctx.beginPath();
      ctx.arc(mx, rulerH + 5, 4, 0, Math.PI * 2);
      ctx.fill();
    });

    handleIn.style.left = `${(inTime / DURATION) * 100}%`;
    handleOut.style.left = `${(outTime / DURATION) * 100}%`;
    playhead.style.left = `${(currentTime / DURATION) * 100}%`;
  }

  function updateUI() {
    document.getElementById('statIn').textContent = fmt(inTime);
    document.getElementById('statOut').textContent = fmt(outTime);
    document.getElementById('statDur').textContent = `${(outTime - inTime).toFixed(1)}s`;
    timeDisplay.innerHTML = `${fmt(currentTime)} <small>/ ${fmt(DURATION)}</small>`;
    playBtn.innerHTML = isPlaying ? '&#10074;&#10074; Pause' : '&#9654; Play';

    // Transcript highlight
    document.querySelectorAll('.cue').forEach((el, idx) => {
      const cue = TRANSCRIPT[idx];
      const active = currentTime >= cue.start && currentTime < cue.end;
      const trimmed = cue.end <= inTime || cue.start >= outTime;
      el.classList.toggle('active', active);
      el.classList.toggle('trimmed', trimmed);
    });

    drawWave();
  }

  function renderTranscript() {
    transcriptList.innerHTML = '';
    TRANSCRIPT.forEach(c => {
      const div = document.createElement('div');
      div.className = 'cue';
      div.innerHTML = `
        <div class="cue-meta">
          <span class="cue-speaker">${c.speaker}</span>
          <span class="mono">${fmt(c.start)} – ${fmt(c.end)}</span>
        </div>
        <div class="cue-text">${c.text}</div>
      `;
      div.addEventListener('click', () => {
        currentTime = c.start;
        updateUI();
      });
      transcriptList.appendChild(div);
    });
  }

  function renderMarkers() {
    markers.sort((a, b) => a.time - b.time);
    document.getElementById('markerCount').textContent = `${markers.length} marker${markers.length === 1 ? '' : 's'}`;
    markerList.innerHTML = '';
    markers.forEach(m => {
      const row = document.createElement('div');
      row.className = 'marker-item';
      row.innerHTML = `
        <button type="button" class="marker-jump">
          <span class="marker-tag mono">${fmt(m.time)}</span>
          <span style="font-size:13.5px;font-weight:500">${m.label.replace(/</g, '&lt;')}</span>
        </button>
        <button type="button" class="marker-del" aria-label="Delete marker">&times;</button>
      `;
      row.querySelector('.marker-jump').addEventListener('click', () => {
        currentTime = m.time;
        updateUI();
      });
      row.querySelector('.marker-del').addEventListener('click', () => {
        markers = markers.filter(x => x.id !== m.id);
        renderMarkers();
        drawWave();
      });
      markerList.appendChild(row);
    });
  }

  function clientXToTime(clientX) {
    const rect = waveStage.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
    return ratio * DURATION;
  }

  // Scrubbing
  waveStage.addEventListener('pointerdown', (e) => {
    if (e.target.closest('.trim-handle')) return;
    waveStage.setPointerCapture(e.pointerId);
    currentTime = clientXToTime(e.clientX);
    updateUI();
    const onMove = (ev) => {
      currentTime = clientXToTime(ev.clientX);
      updateUI();
    };
    const onUp = () => {
      waveStage.removeEventListener('pointermove', onMove);
      waveStage.removeEventListener('pointerup', onUp);
    };
    waveStage.addEventListener('pointermove', onMove);
    waveStage.addEventListener('pointerup', onUp);
  });

  // Trim handles
  function bindHandle(el, isStart) {
    el.addEventListener('pointerdown', (e) => {
      e.stopPropagation();
      el.setPointerCapture(e.pointerId);
      const onMove = (ev) => {
        const t = clientXToTime(ev.clientX);
        if (isStart) {
          inTime = Math.max(0, Math.min(outTime - 1.5, t));
          if (currentTime < inTime) currentTime = inTime;
        } else {
          outTime = Math.min(DURATION, Math.max(inTime + 1.5, t));
          if (currentTime > outTime) currentTime = outTime;
        }
        updateUI();
      };
      const onUp = () => {
        el.removeEventListener('pointermove', onMove);
        el.removeEventListener('pointerup', onUp);
      };
      el.addEventListener('pointermove', onMove);
      el.addEventListener('pointerup', onUp);
    });
  }
  bindHandle(handleIn, true);
  bindHandle(handleOut, false);

  function tick(ts) {
    if (!isPlaying) return;
    if (lastFrame !== null) {
      const dt = (ts - lastFrame) / 1000;
      currentTime += dt;
      if (loopClip && currentTime >= outTime) {
        currentTime = inTime;
      } else if (currentTime >= DURATION) {
        currentTime = 0;
        isPlaying = false;
      }
      updateUI();
    }
    lastFrame = ts;
    if (isPlaying) requestAnimationFrame(tick);
  }

  function togglePlay() {
    isPlaying = !isPlaying;
    lastFrame = null;
    if (isPlaying) {
      if (loopClip && (currentTime < inTime || currentTime >= outTime)) currentTime = inTime;
      requestAnimationFrame(tick);
    }
    updateUI();
  }

  function addMarker(label) {
    markers.push({
      id: ++nextMarkerId,
      time: Math.round(currentTime * 10) / 10,
      label: label || `Marker @ ${fmt(currentTime)}`
    });
    renderMarkers();
    drawWave();
    showToast(`Added marker at ${fmt(currentTime)}`);
  }

  playBtn.addEventListener('click', togglePlay);
  document.getElementById('jumpInBtn').addEventListener('click', () => { currentTime = inTime; updateUI(); });
  document.getElementById('loopBtn').addEventListener('click', (e) => {
    loopClip = !loopClip;
    e.currentTarget.classList.toggle('active', loopClip);
  });
  document.getElementById('setInBtn').addEventListener('click', () => {
    inTime = Math.min(currentTime, outTime - 1.5);
    updateUI();
  });
  document.getElementById('setOutBtn').addEventListener('click', () => {
    outTime = Math.max(currentTime, inTime + 1.5);
    updateUI();
  });
  document.getElementById('quickMarkerBtn').addEventListener('click', () => addMarker(''));
  document.getElementById('markerForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const inp = document.getElementById('markerInput');
    addMarker(inp.value.trim());
    inp.value = '';
  });
  document.getElementById('exportBtn').addEventListener('click', () => {
    showToast(`Queued WAV export: ${fmt(inTime)} → ${fmt(outTime)} (${(outTime - inTime).toFixed(1)}s)`);
  });

  document.addEventListener('keydown', (e) => {
    if (e.target.tagName === 'INPUT') return;
    if (e.code === 'Space') { e.preventDefault(); togglePlay(); }
    else if (e.key.toLowerCase() === 'i') { inTime = Math.min(currentTime, outTime - 1.5); updateUI(); }
    else if (e.key.toLowerCase() === 'o') { outTime = Math.max(currentTime, inTime + 1.5); updateUI(); }
    else if (e.key.toLowerCase() === 'm') { addMarker(''); }
  });

  window.addEventListener('resize', drawWave);
  renderTranscript();
  renderMarkers();
  updateUI();
})();
</script>
</body>
</html>