forked from mattdiamond/Recorderjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecorder.js
95 lines (79 loc) · 2.44 KB
/
recorder.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
(function (window) {
var Recorder = function (source, cfg) {
var config = cfg || {};
var bufferLen = config.bufferLen || 4096;
var numChannels = config.numChannels || 2;
this.context = source.context;
this.node = (this.context.createScriptProcessor || this.context.createJavaScriptNode)
.call(this.context, bufferLen, numChannels, numChannels);
var recording = false,
currCallback;
var worker = new Worker(config.workerPath || 'recorderWorker.js');
worker.postMessage({
command: 'init',
config: {
sampleRate: this.context.sampleRate,
numChannels: numChannels
}
});
this.node.onaudioprocess = function (e) {
if (!recording) return;
var buffer = [];
for (var channel = 0; channel < numChannels; channel++) {
buffer.push(e.inputBuffer.getChannelData(channel));
}
worker.postMessage({
command: 'record',
buffer: buffer
});
};
this.configure = function (cfg) {
for (var prop in cfg) {
if (cfg.hasOwnProperty(prop)) {
config[prop] = cfg[prop];
}
}
};
this.record = function () {
recording = true;
};
this.stop = function () {
recording = false;
};
this.clear = function () {
worker.postMessage({ command: 'clear' });
};
this.getBuffer = function (cb) {
currCallback = cb;
worker.postMessage({ command: 'getBuffer' })
};
this.exportWAV = function (cb) {
this.exportCustomWAV(null, cb);
};
this.exportCustomWAV = function (customSamplingRate, cb) {
currCallback = cb;
if (!currCallback) throw new Error('Callback not set');
worker.postMessage({
command: 'exportWAV',
type: 'audio/wav',
customSamplingRate: customSamplingRate
});
};
worker.onmessage = function (e) {
var blob = e.data;
currCallback(blob);
};
source.connect(this.node);
this.node.connect(this.context.destination); //this should not be necessary
};
Recorder.forceDownload = function (blob, filename) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = window.document.createElement('a');
link.href = url;
link.download = filename || 'output.wav';
var click = document.createEvent("Event");
click.initEvent("click", true, true);
link.dispatchEvent(click);
};
window.Recorder = Recorder;
})(window);