forked from ai/audio-recorder-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmpeg-encoder.js
47 lines (40 loc) · 1.02 KB
/
mpeg-encoder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module.exports = function () {
// eslint-disable-next-line
importScripts('https://cdnjs.cloudflare.com/ajax/libs/lamejs/1.2.0/lame.min.js')
var CHANNELS = 1
var KBPS = 128
var SAMPLE_RATE = 44100
// eslint-disable-next-line
var encoder = new lamejs.Mp3Encoder(CHANNELS, SAMPLE_RATE, KBPS)
var recorded = new Int8Array()
function concat (a, b) {
if (b.length === 0) {
return a
}
var c = new Int8Array(a.length + b.length)
c.set(a)
c.set(b, a.length)
return c
}
function encode (buffer) {
for (var i = 0; i < buffer.length; i++) {
buffer[i] = buffer[i] * 32767.5
}
var buf = encoder.encodeBuffer(buffer)
recorded = concat(recorded, buf)
}
function dump () {
var buf = encoder.flush()
recorded = concat(recorded, buf)
var buffer = recorded.buffer
recorded = new Int8Array()
postMessage(buffer, [buffer])
}
onmessage = function (e) {
if (e.data[0] === 'encode') {
encode(e.data[1])
} else {
dump(e.data[1])
}
}
}