微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AudioContext 未在 JavaScript 中正确设置增益

如何解决AudioContext 未在 JavaScript 中正确设置增益

我正在尝试按照本文将音频元素的音量设置为 1 以上。

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

我需要能够多次设置它,所以我设置了一个全局数组来存储不同的结果,以便我可以根据参与者进行调整。

这似乎不起作用,对我来说,设置增益时我看不出任何区别,我做错了什么吗?

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);
}

我这样称呼它...

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

amplifyMedia(
  `audio-${participantId}`,audioElement,volume // number between 0-2
);

解决方法

那篇文章可能已经过时了。您不应直接分配给增益的值,而应使用 setter 方法。

setValueAtTime 非常简单,应该可以满足您的需求。文档显示了在增益节点上调用此方法的示例。 https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setValueAtTime

还有 setTargetAtTime 稍微复杂一点,但如果您需要更改当前正在播放的内容的设置,听起来应该会更好。 https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setTargetAtTime

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。