Spaces:
Running
Running
File size: 885 Bytes
513b47e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // 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 = [];
}
};
|