WEBRTC:当我们有音频流时,是否可以控制每个音轨的音量?



我的目标是什么?

为了控制每个音轨的音量,所以我可以在较低的音量下播放背景声音,以较高的音量播放其他声音。

场景

  1. 我有一个上传音频文件的页面,上传完成后,会在 DOM 上创建一个音频播放器。
  2. 音频源连接到 audioContext.destination 和 mediaStreamDestination。
  3. 音频流工作正常。

我为每个音频播放器添加了音量范围,并尝试控制音量。

volumeControlInput.addEventListener("change", (event) => {
const audioSource = audioSources[index];
const gainNode = audioContext.createGain();
// Connect source to a gain node
audioSource.connect(gainNode);
// Connect gain node to destination
gainNode.connect(audioContext.destination);
gainNode.connect(mediaStreamDestination); //this doesn't seem necessary but I tried with and without it and it doesn't change anything.
const volume = event.target.value;
const fraction = parseInt(volume) / parseInt(event.target.max); // max is 100
// Using an x*x curve (x-squared) since simple linear (x) does not
// sound as good.
// I also tried setValueAtTime and there's no difference for me.
gainNode.gain.value = fraction * fraction;
}

我试图解决的问题是什么?

只有当我拖动音量范围输入时,音量才会增加,它永远不会调低音量。

对我来说奇怪的是,这个例子在这里工作正常 https://webaudioapi.com/samples/volume/来源: https://github.com/borismus/webaudioapi.com/blob/master/content/posts/volume/volume-sample.js

我想知道这是否根本不可能,有什么想法吗?

看起来您在事件侦听器中创建了一个新GainNode。这样,您可以继续为每个新卷添加连接,但永远不会删除以前的连接。这就解释了为什么你的信号只会变得更响亮。

我建议在事件侦听器之外创建GainNode及其连接。然后,事件侦听器将只处理在gainAudioParam上设置value

最新更新