-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoffscreen.js
67 lines (58 loc) · 2.03 KB
/
offscreen.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
chrome.runtime.onMessage.addListener(async (message) => {
if (message.target === 'offscreen') {
switch (message.type) {
case 'start-recording':
startRecording(message.data);
break;
case 'stop-recording':
stopRecording();
break;
default:
throw new Error('Unrecognized message:', message.type);
}
}
});
let recorder;
let data = [];
async function startRecording(streamId) {
if (recorder?.state === 'recording') {
throw new Error('Called startRecording while recording is in progress.');
}
const media = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: streamId
}
}
});
// Continue to play the captured audio to the user.
const output = new AudioContext();
const source = output.createMediaStreamSource(media);
source.connect(output.destination);
// Start recording.
recorder = new MediaRecorder(media, { mimeType: 'audio/webm' });
recorder.ondataavailable = (event) => data.push(event.data);
recorder.onstop = () => {
const blob = new Blob(data, { type: 'audio/webm' });
window.open(URL.createObjectURL(blob), '_blank');
// Clear state ready for next recording
recorder = undefined;
data = [];
};
recorder.start();
// Record the current state in the URL. This provides a very low-bandwidth
// way of communicating with the service worker (the service worker can check
// the URL of the document and see the current recording state). We can't
// store that directly in the service worker as it may be terminated while
// recording is in progress. We could write it to storage but that slightly
// increases the risk of things getting out of sync.
window.location.hash = 'recording';
}
async function stopRecording() {
recorder.stop();
// Stopping the tracks makes sure the recording icon in the tab is removed.
recorder.stream.getTracks().forEach((t) => t.stop());
// Update current state in URL
window.location.hash = '';
}