assemblyai
Version:
The AssemblyAI JavaScript SDK provides an easy-to-use interface for interacting with the AssemblyAI API, which supports async and real-time transcription, as well as the latest LeMUR models.
20 lines (19 loc) • 2.61 kB
TypeScript
/**
* AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
* native sample rate, resamples to `targetRate` (linear interpolation, stateful
* across `process()` calls), packs to little-endian Int16 PCM, and posts
* fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
*
* `samplesSent` is in **target-rate samples**, so the main thread can derive a
* stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
* frame AAI uses for `StreamingWord.start` / `.end`.
*
* Defined as a string so it can be registered via a Blob URL — the SDK ships as
* a single ESM file, so a separate `.js` worklet asset isn't viable.
*/
export declare const pcm16EncoderWorkletSource = "\nclass Pcm16EncoderProcessor extends AudioWorkletProcessor {\n constructor(options) {\n super();\n const opts = (options && options.processorOptions) || {};\n this.targetRate = opts.targetRate || 16000;\n this.chunkMs = opts.chunkMs || 50;\n this.ratio = sampleRate / this.targetRate;\n this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);\n this.buffer = new Int16Array(this.chunkSize);\n this.bufferIdx = 0;\n this.samplesSent = 0;\n this.lastSample = 0;\n this.fractional = 0;\n }\n\n process(inputs) {\n const input = inputs[0];\n if (!input || input.length === 0 || !input[0] || input[0].length === 0) {\n return true;\n }\n const mono = input[0];\n let pos = this.fractional;\n while (pos < mono.length) {\n const i = Math.floor(pos);\n const frac = pos - i;\n const a = i === 0 ? this.lastSample : mono[i - 1];\n const b = mono[i];\n const sample = a + (b - a) * frac;\n const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;\n this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;\n if (this.bufferIdx === this.chunkSize) {\n const out = new Int16Array(this.chunkSize);\n out.set(this.buffer);\n this.samplesSent += this.chunkSize;\n this.port.postMessage(\n { pcm: out.buffer, samplesSent: this.samplesSent },\n [out.buffer],\n );\n this.bufferIdx = 0;\n }\n pos += this.ratio;\n }\n this.lastSample = mono[mono.length - 1];\n this.fractional = pos - mono.length;\n return true;\n }\n}\nregisterProcessor(\"aai-pcm16-encoder\", Pcm16EncoderProcessor);\n";
export declare const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
export type Pcm16EncoderMessage = {
pcm: ArrayBuffer;
samplesSent: number;
};