mardi 30 juin 2020

Controlling volume of active tab in chrome

Working on a chrome extension and I want to control to audio of the active tab.

Currently this is what I have

let audioStates = {};
window.audioStates = audioStates;
const connectStream = (tabId, stream) => {
  const audioContext = new window.AudioContext();
  const source = audioContext.createMediaStreamSource(stream);
  const gainNode = audioContext.createGain();
  source.connect(gainNode),
    gainNode.connect(audioContext.destination),
    (audioStates[tabId] = {
      audioContext: audioContext,
      gainNode: gainNode,
    });
};
const setGain = (tabId, level, state) => {
  if (state === 'down') {
    audioStates[tabId].gainNode.gain.value =
      audioStates[tabId].gainNode.gain.value * level;
  } else if (state === 'up') {
    audioStates[tabId].gainNode.gain.value =
      audioStates[tabId].gainNode.gain.value / level;
  }
};

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const tab = tabs[0];

        const url = new URL(tab.url);
        activeTab = url.hostname;
        activeTabId = tab.id;
      });

      chrome.tabCapture.capture(
        {
          audio: true,
          video: false,
        },
        (stream) => {
          if (chrome.runtime.lastError) {
            return;
          } else {
            console.log(audioStates);
            connectStream(activeTabId, stream);
            setGain(activeTabId, 0.1, 'down');
          }
        }
      );

I store every tab where the volume is called to be raised and lowered. And use setGain to lower and raise the gain depending on the state, .i.e. up and down.

Is there a simpler way to do this? Storing the tabs feels unnecessary.




Aucun commentaire:

Enregistrer un commentaire