-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
73 lines (61 loc) · 1.99 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
const tabAudioContexts = {};
const tabVolumes = {};
function captureTabAudio(tabId, volume) {
return new Promise((resolve, reject) => {
chrome.tabCapture.capture(
{
audio: true,
video: false,
},
(stream) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
reject(chrome.runtime.lastError.message);
return;
}
const audioContext = new AudioContext();
const gainNode = audioContext.createGain();
const sourceNode = audioContext.createMediaStreamSource(stream);
sourceNode.connect(gainNode);
gainNode.connect(audioContext.destination);
tabAudioContexts[tabId] = { audioContext, gainNode, sourceNode, stream };
gainNode.gain.value = volume;
tabVolumes[tabId] = volume;
resolve();
}
);
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'setVolume') {
const tabId = request.tabId;
const volume = request.volume;
if (!tabAudioContexts[tabId]) {
captureTabAudio(tabId, volume)
.then(() => {
sendResponse({ success: true });
})
.catch((error) => {
alert(error);
sendResponse({ success: false, error });
});
} else {
tabAudioContexts[tabId].gainNode.gain.value = volume;
tabVolumes[tabId] = volume;
sendResponse({ success: true });
}
return true; // Indica que la respuesta se enviará de forma asíncrona.
}
if (request.action === 'getVolume') {
const tabId = request.tabId;
const volume = tabVolumes[tabId] || 1; // Devolver el valor del volumen o 1 por defecto
sendResponse({ volume });
}
});
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
if (tabAudioContexts[tabId]) {
tabAudioContexts[tabId].audioContext.close();
tabAudioContexts[tabId].stream.getAudioTracks()[0].stop();
delete tabAudioContexts[tabId];
}
});