javascript - 如何控制(音频缓冲区)AudioContext() 的音量?

标签 javascript audio audiobuffer

我在 JavaScript 中有以下 AudioContext() 声音对象。
它的体积是100%。我想以 10% 的音量播放它的音量(其中音量 = 0.1)。
如何将其音量降低到 10%?

const aCtx = new AudioContext();
let source = aCtx.createBufferSource();
let buf;
fetch('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav') // can be XHR as well
  .then(resp => resp.arrayBuffer())
  .then(buf => aCtx.decodeAudioData(buf)) // can be callback as well
  .then(decoded => {
    source.buffer = buf = decoded;
    source.loop = true;
    source.connect(aCtx.destination);
    check.disabled = false;
  });

check.onchange = e => {
  if (check.checked) {
    source.start(0); // start our bufferSource
  } else {
    source.stop(0); // this destroys the buffer source
    source = aCtx.createBufferSource(); // so we need to create a new one
    source.buffer = buf;
    source.loop = true;
    source.connect(aCtx.destination);
  }
};
<label>Start Playing</label>
<input type="checkbox" id="check" disabled><br>
<br>Its volume is 100%. Please help me to reduce it to 10%.

最佳答案

我们使用 GainNodes控制音量。

var gainNode = aCtx.createGain()
gainNode.gain.value = 0.1 // 10 %
gainNode.connect(aCtx.destination)

// now instead of connecting to aCtx.destination, connect to the gainNode
source.connect(gainNode)

解决方案

const aCtx = new AudioContext();

const gainNode = aCtx.createGain();
gainNode.gain.value = 0.1; // setting it to 10%
gainNode.connect(aCtx.destination);

let source = aCtx.createBufferSource();
let buf;
fetch('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav') // can be XHR as well
  .then(resp => resp.arrayBuffer())
  .then(buf => aCtx.decodeAudioData(buf)) // can be callback as well
  .then(decoded => {
    source.buffer = buf = decoded;
    source.loop = true;
    source.connect(gainNode);

    check.disabled = false;
  });

check.onchange = e => {
  if (check.checked) {
    source.start(0); // start our bufferSource
  } else {
    source.stop(0); // this destroys the buffer source
    source = aCtx.createBufferSource(); // so we need to create a new one
    source.buffer = buf;
    source.loop = true;
    source.connect(gainNode);
    
  }
};
<label>Start Playing</label>
<input type="checkbox" id="check" disabled><br>
<br>Its volume is 100%. Please help me to reduce it to 10%.

关于javascript - 如何控制(音频缓冲区)AudioContext() 的音量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43386277/

相关文章:

javascript - 如何使用 JavaScript 从选项列表中选择选项

Javascript 和 https - 获取相对路径的 XMLHttpRequest 对象 - 是协议(protocol)/端口 'inherited'?

html - 是否可以用HTML5播放SHOUTcast提供的AAC?

c++ - MMDevice API 中的 CoCreateInstance 返回错误代码 0x800401F0

android - 同时播放多个音频文件

javascript - 如何创建并正确调度AudioBufferSource节点?

audio - 未捕获的TypeError:值不是AudioBuffer类型的

javascript - 如何在网络音频 API 中反向播放但同时保留正向版本?

javascript - 比较两个数组并将公共(public)对象添加到新数组

javascript - 将 html 打印到多个页面