2

I am trying to set volume over 1 on an audio element, following this article.

https://cwestblog.com/2017/08/17/html5-getting-more-volume-from-the-web-audio-api/

I need to be able to set it more than once, so i've set a global array to store the different results in so that I can adjust based on participants.

This does not seem to be working though, to me I can't tell any difference when the gain is set, am I doing something wrong?

window.audioGainParticipants = [];

function amplifyMedia(participant_id, mediaElem, multiplier) {
  const exists = window.audioGainParticipants.find(
    (x) => x.participant_id === participant_id
  );

  let result = null;

  if (exists) {
    result = exists.result;
  } else {
    var context = new (window.AudioContext || window.webkitAudioContext)();

    result = {
      context: context,
      source: context.createMediaElementSource(mediaElem),
      gain: context.createGain(),
      media: mediaElem,
      amplify: function (multiplier) {
        result.gain.gain.value = multiplier;
      },
      getAmpLevel: function () {
        return result.gain.gain.value;
      },
    };
    result.source.connect(result.gain);
    result.gain.connect(context.destination);
    window.audioGainParticipants.push({ participant_id, result });
  }

  result.amplify(multiplier);
}

I call this like this...

const audioElement = document.getElementById(
  `audio-${participantId}`
);

amplifyMedia(
  `audio-${participantId}`,
  audioElement,
  volume // number between 0-2
);
user3284707
  • 3,033
  • 3
  • 35
  • 69

1 Answers1

0

That article might be outdated. You're not supposed to directly assign to the gain's value, but instead use a setter method.

setValueAtTime is pretty simple, and should meet your needs. The docs show an example of calling this method on a gain node. https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setValueAtTime

There's also setTargetAtTime which is a tiny bit more complex, but should sound better if you need to change settings on something that is currently playing. https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setTargetAtTime

Raphael Serota
  • 2,157
  • 10
  • 17