-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
65 lines (58 loc) · 1.88 KB
/
Copy pathbackground.js
File metadata and controls
65 lines (58 loc) · 1.88 KB
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
let creatingOffscreen = null;
async function ensureOffscreenDocument() {
const offscreenUrl = chrome.runtime.getURL('offscreen.html');
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT'],
documentUrls: [offscreenUrl]
});
if (existingContexts.length > 0) return;
if (creatingOffscreen) {
await creatingOffscreen;
} else {
creatingOffscreen = chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Route tab audio to specific hardware output devices'
});
await creatingOffscreen;
creatingOffscreen = null;
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'ROUTE_TAB_AUDIO') {
handleAudioRouting(message.tabId, message.deviceId, message.volume);
}
});
async function handleAudioRouting(tabId, deviceId, volume) {
// Ensure the offscreen document is alive
await ensureOffscreenDocument();
let streamId;
try {
// 1. Try to get a media stream ID for the target tab
streamId = await chrome.tabCapture.getMediaStreamId({
targetTabId: tabId
});
} catch (error) {
// If it fails because the stream is already active, we can just change the sink
if (error.message && (error.message.includes('active stream') || error.message.includes('already being captured'))) {
console.log('Tab already captured, changing sink instead.');
chrome.runtime.sendMessage({
action: 'CHANGE_SINK',
tabId: tabId,
deviceId: deviceId
});
return;
} else {
console.error('Error capturing tab:', error);
return;
}
}
// 2. If we got a new streamId, send it to offscreen.js to play
chrome.runtime.sendMessage({
action: 'PLAY_STREAM_ON_DEVICE',
streamId: streamId,
tabId: tabId,
deviceId: deviceId,
volume: volume
});
}