Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active June 26, 2025 18:52
Show Gist options
  • Save matiaslopezd/e715c9b5e69d4dbadb05027e11740ca7 to your computer and use it in GitHub Desktop.
Save matiaslopezd/e715c9b5e69d4dbadb05027e11740ca7 to your computer and use it in GitHub Desktop.
Amplify audio/video source Javascript
function amplify(node, gain) {
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(node);
// create a gain node
const gainNode = audioCtx.createGain();
gainNode.gain.value = gain;
source.connect(gainNode);
// connect the gain node to an output destination
gainNode.connect(audioCtx.destination);
}
function amplify(node,gain){const audioCtx=new AudioContext();const source=audioCtx.createMediaElementSource(node);const gainNode=audioCtx.createGain();gainNode.gain.value=gain;source.connect(gainNode);gainNode.connect(audioCtx.destination)}
@Saiful-Islam-Sakib
Copy link

Saiful-Islam-Sakib commented Jun 4, 2025

Nice work @matiaslopezd
However, if the line amplify(document.querySelector('video')); gets executed more than one time it will generate an error saying,

Uncaught InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.

We can work around the issue by tweaking the function a bit.

function amplify(node, gain = 2) {
  // Reuse existing AudioContext if available
  if (!node._audioCtx) {
    node._audioCtx = new AudioContext();
    node._sourceNode = node._audioCtx.createMediaElementSource(node);
    node._gainNode = node._audioCtx.createGain();

    node._sourceNode.connect(node._gainNode);
    node._gainNode.connect(node._audioCtx.destination);
  }

  // Just update gain
  node._gainNode.gain.value = gain;
}

With the updated code in place, the volume can be adjusted dynamically at any time by invoking the function in the browser console.
e.g.

amplify(document.querySelector('video'), 2); // increase 
amplify(document.querySelector('video'), 0.5); // decrease

@matiaslopezd
Copy link
Author

matiaslopezd commented Jun 4, 2025

@Saiful-Islam-Sakib thank you! I wrote this before I discovered the extension Volume Master. In my opinion, just use the extension 😄

@Saiful-Islam-Sakib
Copy link

@Saiful-Islam-Sakib thank you! I wrote this before I discovered the extension Volume Master. In my opinion, just use the extension 😄

There's no doubt the extension is great, but I prefer using the code instead I’d rather not have any extensions running in the background 😅
Btw thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment