-
Notifications
You must be signed in to change notification settings - Fork 0
/
offscreen.js
55 lines (47 loc) · 1.49 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
let audioContext = null;
let soundSource = null;
let gainNode = null;
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.type === "handleSound") {
await handleSoundscape(message.soundType);
}
});
async function handleSoundscape(type) {
try {
if (soundSource) {
soundSource.stop();
soundSource = null;
}
if (!audioContext) {
audioContext = new AudioContext();
gainNode = audioContext.createGain();
gainNode.connect(audioContext.destination);
}
if (type !== "none") {
const soundUrl = chrome.runtime.getURL(`sounds/${type}.mp3`);
try {
const response = await fetch(soundUrl);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
soundSource = audioContext.createBufferSource();
soundSource.buffer = audioBuffer;
soundSource.loop = true;
gainNode.gain.value = 0.3;
soundSource.connect(gainNode);
soundSource.start();
} catch (error) {
console.error('Error loading or playing sound:', error);
chrome.runtime.sendMessage({
type: "soundError",
error: "Failed to load sound"
});
}
}
} catch (error) {
console.error('Error initializing audio context:', error);
chrome.runtime.sendMessage({
type: "soundError",
error: "Failed to initialize audio"
});
}
}