forked from normful/Chrome-Audio-Capturer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
315 lines (286 loc) · 9.54 KB
/
background.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
const extend = function() { //helper function to merge objects
let target = arguments[0],
sources = [].slice.call(arguments, 1);
for (let i = 0; i < sources.length; ++i) {
let src = sources[i];
for (key in src) {
let val = src[key];
target[key] = typeof val === "object"
? extend(typeof target[key] === "object" ? target[key] : {}, val)
: val;
}
}
return target;
};
const WORKER_FILE = {
wav: "WavWorker.js",
mp3: "Mp3Worker.js"
};
// default configs
const CONFIGS = {
workerDir: "/workers/", // worker scripts dir (end with /)
numChannels: 2, // number of channels
encoding: "wav", // encoding (can be changed at runtime)
// runtime options
options: {
timeLimit: 1200, // recording time limit (sec)
encodeAfterRecord: true, // process encoding after recording
progressInterval: 1000, // encoding progress report interval (millisec)
bufferSize: undefined, // buffer size (use browser default)
// encoding-specific options
wav: {
mimeType: "audio/wav"
},
mp3: {
mimeType: "audio/mpeg",
bitRate: 192 // (CBR only): bit rate = [64 .. 320]
}
}
};
class Recorder {
constructor(source, configs) { //creates audio context from the source and connects it to the worker
extend(this, CONFIGS, configs || {});
this.context = source.context;
if (this.context.createScriptProcessor == null)
this.context.createScriptProcessor = this.context.createJavaScriptNode;
this.input = this.context.createGain();
source.connect(this.input);
this.buffer = [];
this.initWorker();
}
isRecording() {
return this.processor != null;
}
setEncoding(encoding) {
if(!this.isRecording() && this.encoding !== encoding) {
this.encoding = encoding;
this.initWorker();
}
}
setOptions(options) {
if (!this.isRecording()) {
extend(this.options, options);
this.worker.postMessage({ command: "options", options: this.options});
}
}
startRecording() {
if(!this.isRecording()) {
let numChannels = this.numChannels;
let buffer = this.buffer;
let worker = this.worker;
this.processor = this.context.createScriptProcessor(
this.options.bufferSize,
this.numChannels, this.numChannels);
this.input.connect(this.processor);
this.processor.connect(this.context.destination);
this.processor.onaudioprocess = function(event) {
for (var ch = 0; ch < numChannels; ++ch)
buffer[ch] = event.inputBuffer.getChannelData(ch);
worker.postMessage({ command: "record", buffer: buffer });
};
this.worker.postMessage({
command: "start",
bufferSize: this.processor.bufferSize
});
this.startTime = Date.now();
}
}
cancelRecording() {
if(this.isRecording()) {
this.input.disconnect();
this.processor.disconnect();
delete this.processor;
this.worker.postMessage({ command: "cancel" });
}
}
finishRecording() {
if (this.isRecording()) {
this.input.disconnect();
this.processor.disconnect();
delete this.processor;
this.worker.postMessage({ command: "finish" });
}
}
cancelEncoding() {
if (this.options.encodeAfterRecord)
if (!this.isRecording()) {
this.onEncodingCanceled(this);
this.initWorker();
}
}
initWorker() {
if (this.worker != null)
this.worker.terminate();
this.onEncoderLoading(this, this.encoding);
this.worker = new Worker(this.workerDir + WORKER_FILE[this.encoding]);
let _this = this;
this.worker.onmessage = function(event) {
let data = event.data;
switch (data.command) {
case "loaded":
_this.onEncoderLoaded(_this, _this.encoding);
break;
case "timeout":
_this.onTimeout(_this);
break;
case "progress":
_this.onEncodingProgress(_this, data.progress);
break;
case "complete":
_this.onComplete(_this, data.blob);
}
}
this.worker.postMessage({
command: "init",
config: {
sampleRate: this.context.sampleRate,
numChannels: this.numChannels
},
options: this.options
});
}
onEncoderLoading(recorder, encoding) {}
onEncoderLoaded(recorder, encoding) {}
onTimeout(recorder) {}
onEncodingProgress(recorder, progress) {}
onEncodingCanceled(recorder) {}
onComplete(recorder, blob) {}
}
const audioCapture = (timeLimit, muteTab, format, quality, limitRemoved) => {
chrome.tabCapture.capture({audio: true}, (stream) => { // sets up stream for capture
let startTabId; //tab when the capture is started
let timeout;
let completeTabID; //tab when the capture is stopped
let audioURL = null; //resulting object when encoding is completed
chrome.tabs.query({active:true, currentWindow: true}, (tabs) => startTabId = tabs[0].id) //saves start tab
const liveStream = stream;
const audioCtx = new AudioContext();
const source = audioCtx.createMediaStreamSource(stream);
let mediaRecorder = new Recorder(source); //initiates the recorder based on the current stream
mediaRecorder.setEncoding(format); //sets encoding based on options
if(limitRemoved) { //removes time limit
mediaRecorder.setOptions({timeLimit: 10800});
} else {
mediaRecorder.setOptions({timeLimit: timeLimit/1000});
}
if(format === "mp3") {
mediaRecorder.setOptions({mp3: {bitRate: quality}});
}
mediaRecorder.startRecording();
function onStopCommand(command) { //keypress
if (command === "stop") {
stopCapture();
}
}
function onStopClick(request) { //click on popup
if(request === "stopCapture") {
stopCapture();
} else if (request === "cancelCapture") {
cancelCapture();
} else if (request.cancelEncodeID) {
if(request.cancelEncodeID === startTabId && mediaRecorder) {
mediaRecorder.cancelEncoding();
}
}
}
chrome.commands.onCommand.addListener(onStopCommand);
chrome.runtime.onMessage.addListener(onStopClick);
mediaRecorder.onComplete = (recorder, blob) => {
audioURL = window.URL.createObjectURL(blob);
if(completeTabID) {
chrome.tabs.sendMessage(completeTabID, {type: "encodingComplete", audioURL});
}
mediaRecorder = null;
}
mediaRecorder.onEncodingProgress = (recorder, progress) => {
if(completeTabID) {
chrome.tabs.sendMessage(completeTabID, {type: "encodingProgress", progress: progress});
}
}
const stopCapture = function() {
let endTabId;
//check to make sure the current tab is the tab being captured
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
endTabId = tabs[0].id;
if(mediaRecorder && startTabId === endTabId){
mediaRecorder.finishRecording();
chrome.tabs.create({url: "complete.html"}, (tab) => {
completeTabID = tab.id;
let completeCallback = () => {
chrome.tabs.sendMessage(tab.id, {type: "createTab", format: format, audioURL, startID: startTabId});
}
setTimeout(completeCallback, 500);
});
closeStream(endTabId);
}
})
}
const cancelCapture = function() {
let endTabId;
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
endTabId = tabs[0].id;
if(mediaRecorder && startTabId === endTabId){
mediaRecorder.cancelRecording();
closeStream(endTabId);
}
})
}
//removes the audio context and closes recorder to save memory
const closeStream = function(endTabId) {
chrome.commands.onCommand.removeListener(onStopCommand);
chrome.runtime.onMessage.removeListener(onStopClick);
mediaRecorder.onTimeout = () => {};
audioCtx.close();
liveStream.getAudioTracks()[0].stop();
sessionStorage.removeItem(endTabId);
chrome.runtime.sendMessage({captureStopped: endTabId});
}
mediaRecorder.onTimeout = stopCapture;
if(!muteTab) {
let audio = new Audio();
audio.srcObject = liveStream;
audio.play();
}
});
}
//sends reponses to and from the popup menu
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.currentTab && sessionStorage.getItem(request.currentTab)) {
sendResponse(sessionStorage.getItem(request.currentTab));
} else if (request.currentTab){
sendResponse(false);
} else if (request === "startCapture") {
startCapture();
}
});
const startCapture = function() {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
// CODE TO BLOCK CAPTURE ON YOUTUBE, DO NOT REMOVE
// if(tabs[0].url.toLowerCase().includes("youtube")) {
// chrome.tabs.create({url: "error.html"});
// } else {
if(!sessionStorage.getItem(tabs[0].id)) {
sessionStorage.setItem(tabs[0].id, Date.now());
chrome.storage.sync.get({
maxTime: 1200000,
muteTab: false,
format: "mp3",
quality: 192,
limitRemoved: false
}, (options) => {
let time = options.maxTime;
if(time > 1200000) {
time = 1200000
}
audioCapture(time, options.muteTab, options.format, options.quality, options.limitRemoved);
});
chrome.runtime.sendMessage({captureStarted: tabs[0].id, startTime: Date.now()});
}
// }
});
};
chrome.commands.onCommand.addListener((command) => {
if (command === "start") {
startCapture();
}
});