// Encodes PCM chunks to MP3 off the main thread, as they arrive. import { Mp3Encoder } from '../vendor/lamejs/lamejs.js'; let enc = null, parts = [], job = 0; onmessage = ({ data }) => { if (data.type === 'start') { job = data.job; parts = []; enc = new Mp3Encoder(1, data.sampleRate, data.kbps || 64); } else if (data.type === 'chunk' && data.job === job && enc) { const pcm = data.pcm, step = 1152 * 16; for (let i = 0; i < pcm.length; i += step) { const b = enc.encodeBuffer(pcm.subarray(i, i + step)); if (b.length) parts.push(b); } postMessage({ type: 'encoded', job, index: data.index }); } else if (data.type === 'finish' && data.job === job && enc) { const b = enc.flush(); if (b.length) parts.push(b); postMessage({ type: 'done', job, blob: new Blob(parts, { type: 'audio/mpeg' }) }); enc = null; parts = []; } };