From e28dcbfb4ce084ce7d023548b09839d703cdf3ff Mon Sep 17 00:00:00 2001 From: pliny <133052465+elder-plinius@users.noreply.github.com> Date: Sat, 12 Aug 2023 17:10:43 -0700 Subject: [PATCH] Update background.js --- background.js | 68 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/background.js b/background.js index 7033420..be6372a 100644 --- a/background.js +++ b/background.js @@ -1,19 +1,53 @@ -chrome.runtime.onInstalled.addListener(() => { - chrome.storage.sync.set({frequency: '440'}); -}); +let audioContext; +let oscillatorLeft; +let oscillatorRight; +let gainNode; +let isPlaying = false; -chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { - if (changeInfo.status === 'complete' && /^http/.test(tab.url)) { - chrome.scripting.executeScript({ - target: {tabId: tabId}, - files: ['binauralGenerator.js'] - }); - } -}); +function startBinauralBeats(frequency, delta, volume) { + if (audioContext) { + audioContext.close(); + } -chrome.action.onClicked.addListener((tab) => { - chrome.scripting.executeScript({ - target: {tabId: tab.id}, - files: ['binauralGenerator.js'] - }); -}); \ No newline at end of file + audioContext = new AudioContext(); + + oscillatorLeft = audioContext.createOscillator(); + oscillatorRight = audioContext.createOscillator(); + gainNode = audioContext.createGain(); + + oscillatorLeft.frequency.setValueAtTime(frequency, audioContext.currentTime); + oscillatorRight.frequency.setValueAtTime(frequency + delta, audioContext.currentTime); + + gainNode.gain.setValueAtTime(volume, audioContext.currentTime); + + oscillatorLeft.connect(gainNode); + oscillatorRight.connect(gainNode); + gainNode.connect(audioContext.destination); + + oscillatorLeft.start(); + oscillatorRight.start(); + + isPlaying = true; +} + +function stopBinauralBeats() { + if (oscillatorLeft) { + oscillatorLeft.stop(); + } + if (oscillatorRight) { + oscillatorRight.stop(); + } + isPlaying = false; +} + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.action === 'togglePlayPause') { + if (isPlaying) { + stopBinauralBeats(); + sendResponse({ status: 'paused' }); + } else { + startBinauralBeats(message.frequency, message.delta, message.volume); + sendResponse({ status: 'playing' }); + } + } +});