Spaces:
Running
Running
Add MP3 encoding worker
Browse files- src/mp3-worker.js +22 -0
src/mp3-worker.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Encodes PCM chunks to MP3 off the main thread, as they arrive.
|
| 2 |
+
import { Mp3Encoder } from '../vendor/lamejs/lamejs.js';
|
| 3 |
+
|
| 4 |
+
let enc = null, parts = [], job = 0;
|
| 5 |
+
onmessage = ({ data }) => {
|
| 6 |
+
if (data.type === 'start') {
|
| 7 |
+
job = data.job; parts = [];
|
| 8 |
+
enc = new Mp3Encoder(1, data.sampleRate, data.kbps || 64);
|
| 9 |
+
} else if (data.type === 'chunk' && data.job === job && enc) {
|
| 10 |
+
const pcm = data.pcm, step = 1152 * 16;
|
| 11 |
+
for (let i = 0; i < pcm.length; i += step) {
|
| 12 |
+
const b = enc.encodeBuffer(pcm.subarray(i, i + step));
|
| 13 |
+
if (b.length) parts.push(b);
|
| 14 |
+
}
|
| 15 |
+
postMessage({ type: 'encoded', job, index: data.index });
|
| 16 |
+
} else if (data.type === 'finish' && data.job === job && enc) {
|
| 17 |
+
const b = enc.flush();
|
| 18 |
+
if (b.length) parts.push(b);
|
| 19 |
+
postMessage({ type: 'done', job, blob: new Blob(parts, { type: 'audio/mpeg' }) });
|
| 20 |
+
enc = null; parts = [];
|
| 21 |
+
}
|
| 22 |
+
};
|