How do you transcribe long audio files exceeding 25 MB with Whisper API by chunking on silence boundaries? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you transcribe long audio files exceeding 25 MB with Whisper API by chunking on silence boundaries?

message-square
0

Overview

OpenAI’s audio transcription endpoint enforces a strict 25 MB limit on the total HTTP multipart request body (26,214,400 bytes, including form fields and multipart boundaries). When transcribing long audio files exceeding 25 MB, slicing at silence boundaries prevents mid-word/mid-sentence cuts while keeping each uploaded chunk safely below the request cap (target ~20–24 MB).

  • Downmix and compress for speech first: Speech recognition does not need high-bitrate stereo or uncompressed PCM; downmixing to mono and encoding to voice-friendly MP3 or Opus shrinks file size dramatically before chunking.
  • Stream/detect silence with ffmpeg (silencedetect) instead of decoding hours of PCM in memory: Using ffmpeg avoids huge RAM spikes on multi-hour recordings and locates natural pauses (silence_start / silence_end) where cut points won’t clip syllables.
  • Enforce duration and byte budgets with cumulative timestamp offsets: Group speech segments up to a safe byte/duration ceiling (splitting on silence mid-pause when needed), track each chunk’s exact start offset in seconds, and add that offset back to segment/word timestamps during reassembly.

Steps

  1. Normalize audio to mono speech format: Convert or extract audio via ffmpeg to mono (e.g., 16 kHz or 24–32 kbps mono MP3/Opus) so file sizes stay compact and predictable across chunks.
  2. Detect silence intervals with ffmpeg -af silencedetect: Run silencedetect (such as n=-35dB:d=0.4) to parse silence_start, silence_end, and silence_duration events across the audio timeline.
  3. Plan cut points at silence midpoints within size/duration limits: Select silence midpoints that keep each chunk well under ~20–24 MB (and bounded in duration), adding a small padding buffer (e.g., 150–250 ms) around pauses so initial consonants are not clipped.
  4. Transcribe chunks with retries and reassemble with time offsets: Upload each chunk under 25 MB to the transcriptions API with bounded retries, persist per-chunk results for resume safety, and shift returned timestamps by each chunk’s startSec offset.

Example

import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import { createReadStream } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import OpenAI from "openai";

const execFileAsync = promisify(execFile);
const openai = new OpenAI();

export interface SilenceWindow {
  startSec: number;
  endSec: number;
  midpointSec: number;
}

export interface AudioChunkSpec {
  index: number;
  filePath: string;
  startSec: number;
  endSec: number;
  sizeBytes: number;
}

export interface AlignedSegment {
  text: string;
  startSec: number;
  endSec: number;
  chunkIndex: number;
}

/**
 * Detects silent intervals using ffmpeg's `silencedetect` filter.
 */
export async function detectSilenceWindows(
  inputPath: string,
  noiseDb = -35,
  minSilenceSec = 0.4
): Promise<SilenceWindow[]> {
  const { stderr } = await execFileAsync(
    "ffmpeg",
    [
      "-hide_banner",
      "-nostats",
      "-i",
      inputPath,
      "-af",
      `silencedetect=n=${noiseDb}dB:d=${minSilenceSec}`,
      "-f",
      "null",
      "-",
    ],
    { maxBuffer: 20 * 1024 * 1024 }
  );

  const windows: SilenceWindow[] = [];
  let pendingStart: number | null = null;

  for (const line of stderr.split(/\r?\n/)) {
    const startMatch = line.match(/silence_start:\s*([0-9.]+)/);
    if (startMatch) {
      pendingStart = Number(startMatch[1]);
      continue;
    }

    const endMatch = line.match(/silence_end:\s*([0-9.]+)/);
    if (endMatch && pendingStart !== null) {
      const endSec = Number(endMatch[1]);
      if (Number.isFinite(pendingStart) && Number.isFinite(endSec) && endSec > pendingStart) {
        windows.push({
          startSec: pendingStart,
          endSec,
          midpointSec: (pendingStart + endSec) / 2,
        });
      }
      pendingStart = null;
    }
  }

  return windows;
}

async function probeDurationSec(filePath: string): Promise<number> {
  const { stdout } = await execFileAsync("ffprobe", [
    "-v",
    "error",
    "-show_entries",
    "format=duration",
    "-of",
    "default=noprint_wrappers=1:nokey=1",
    filePath,
  ]);
  const dur = Number(stdout.trim());
  return Number.isFinite(dur) && dur > 0 ? dur : 0;
}

/**
 * Transcodes input to voice-friendly mono MP3, detects silences, and slices
 * into chunks kept safely below the 25 MB Whisper upload limit.
 */
export async function splitAudioOnSilence(
  sourceAudioPath: string,
  workDir: string,
  options?: {
    maxChunkBytes?: number; // Default 20 MB to leave ample margin below 25 MB multipart cap
    maxChunkSec?: number; // Default 900s (15 min)
    bitrateKbps?: number; // Default 48 kbps mono speech MP3
  }
): Promise<AudioChunkSpec[]> {
  const maxChunkBytes = options?.maxChunkBytes ?? 20 * 1024 * 1024;
  const maxChunkSec = options?.maxChunkSec ?? 900;
  const bitrateKbps = options?.bitrateKbps ?? 48;

  await fs.mkdir(workDir, { recursive: true });
  const normalizedPath = path.join(workDir, "normalized_mono.mp3");

  // 1. Convert to mono speech MP3 so duration/byte ratio is predictable
  await execFileAsync("ffmpeg", [
    "-y",
    "-hide_banner",
    "-loglevel",
    "error",
    "-i",
    sourceAudioPath,
    "-vn",
    "-ac",
    "1",
    "-ar",
    "16000",
    "-b:a",
    `${bitrateKbps}k`, normalizedPath, ]);  const totalDurationSec = await probeDurationSec(normalizedPath); const stat = await fs.stat(normalizedPath); const bytesPerSec = totalDurationSec > 0 ? stat.size / totalDurationSec : (bitrateKbps * 1000) / 8;  // Estimate safe max duration per chunk from byte ceiling const byteDerivedMaxSec = Math.max(30, Math.floor((maxChunkBytes * 0.9) / Math.max(1, bytesPerSec))); const effectiveMaxSec = Math.min(maxChunkSec, byteDerivedMaxSec);  const silences = await detectSilenceWindows(normalizedPath, -35, 0.4); const cutPoints: number[] = [];  let currentStart = 0; while (currentStart + effectiveMaxSec < totalDurationSec) { const idealMaxCut = currentStart + effectiveMaxSec; const minSearchCut = currentStart + effectiveMaxSec * 0.5;  // Prefer a silence midpoint in the upper half of the window; fallback to any silence before limit const candidateSilences = silences.filter( (s) => s.midpointSec >= minSearchCut && s.midpointSec <= idealMaxCut ); const fallbackSilences = candidateSilences.length > 0 ? candidateSilences : silences.filter((s) => s.midpointSec > currentStart && s.midpointSec <= idealMaxCut);  const chosenCut = fallbackSilences.length > 0 ? fallbackSilences[fallbackSilences.length - 1].midpointSec : idealMaxCut;  cutPoints.push(chosenCut); currentStart = chosenCut; }  const boundaries = [0, ...cutPoints, totalDurationSec]; const chunks: AudioChunkSpec[] = [];  for (let i = 0; i < boundaries.length - 1; i++) { const startSec = boundaries[i]; const endSec = boundaries[i + 1]; const durationSec = Math.max(0.1, endSec - startSec); const chunkFile = path.join(workDir, `chunk_${String(i).padStart(4, "0")}.mp3`);

    await execFileAsync("ffmpeg", [
      "-y",
      "-hide_banner",
      "-loglevel",
      "error",
      "-ss",
      startSec.toFixed(3),
      "-t",
      durationSec.toFixed(3),
      "-i",
      normalizedPath,
      "-c",
      "copy",
      chunkFile,
    ]);

    const chunkStat = await fs.stat(chunkFile);
    if (chunkStat.size > 24.5 * 1024 * 1024) {
      throw new Error(`Chunk ${chunkFile} exceeded 24.5 MB (${chunkStat.size} bytes)`);
    }

    chunks.push({
      index: i,
      filePath: chunkFile,
      startSec,
      endSec,
      sizeBytes: chunkStat.size,
    });
  }

  return chunks;
}

/**
 * Transcribes each chunk sequentially (or with bounded concurrency) and shifts
 * returned segment timestamps by each chunk's starting offset.
 */
export async function transcribeLongAudioWithSilenceChunks(
  sourceAudioPath: string,
  workDir: string,
  language?: string
): Promise<{ fullText: string; segments: AlignedSegment[] }> {
  const chunks = await splitAudioOnSilence(sourceAudioPath, workDir);
  const allSegments: AlignedSegment[] = [];
  const textParts: string[] = [];
  let previousTailPrompt = "";

  for (const chunk of chunks) {
    const response = await openai.audio.transcriptions.create({
      file: createReadStream(chunk.filePath),
      model: "whisper-1",
      response_format: "verbose_json",
      ...(language ? { language } : {}),
      ...(previousTailPrompt ? { prompt: previousTailPrompt.slice(-220) } : {}),
    });

    const chunkText = response.text?.trim() ?? "";
    if (chunkText) {
      textParts.push(chunkText);
      previousTailPrompt = chunkText;
    }

    for (const seg of response.segments ?? []) {
      allSegments.push({
        text: seg.text.trim(),
        startSec: Number((chunk.startSec + seg.start).toFixed(3)),
        endSec: Number((chunk.startSec + seg.end).toFixed(3)),
        chunkIndex: chunk.index,
      });
    }
  }

  return {
    fullText: textParts.join(" ").trim(),
    segments: allSegments,
  };
}

Tips

  • Leave headroom below 25 MB (26,214,400 bytes): Multipart form headers, field names, and boundary markers add overhead to the HTTP request body—keep individual audio files under ~20–24 MB so borderline chunks never hit a 413 rejection.
  • Tune silence thresholds for noisy recordings: In noisy rooms or phone calls, background noise may stay above -35dB; inspect silencedetect output on a sample file and adjust n (noise floor in dB) and d (minimum pause duration in seconds) rather than guessing blindly.
  • Persist per-chunk outputs and clean up temp files: Save each chunk’s transcript to disk/object store keyed by chunk index so a transient rate limit or network error on chunk 8 does not discard chunks 1–7, and remove temporary audio chunks in a finally block.