BaseAudioContext: createGain() 方法
BaseAudioContext 接口的 createGain() 方法创建一个 GainNode,该节点可用于控制整个音频图的增益(或音量)。
注意: 创建 GainNode 的推荐方式是使用 GainNode() 构造函数;请参阅 创建 AudioNode。
语法
js
createGain()
参数
无。
返回值
一个 GainNode,它接收一个或多个音频源作为输入,并输出音量已根据节点的 GainNode.gain a-rate 参数调整到指定级别的音频。
示例
下面的示例展示了如何使用 AudioContext 创建一个 GainNode,然后通过更改 gain 属性值来静音和取消静音音频(在用户点击“静音”按钮时)。
下面的代码片段无法独立运行——有关完整的可运行示例,请查看我们的 Voice-change-O-matic 演示 (查看源代码)。
html
<div>
<button class="mute">Mute button</button>
</div>
js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const mute = document.querySelector(".mute");
let source;
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(
// constraints - only audio needed for this app
{
audio: true,
},
// Success callback
(stream) => {
source = audioCtx.createMediaStreamSource(stream);
},
// Error callback
(err) => {
console.error(`The following gUM error occurred: ${err}`);
},
);
} else {
console.error("getUserMedia not supported on your browser!");
}
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
// …
mute.onclick = () => {
if (mute.id === "") {
// 0 means mute. If you still hear something, make sure you haven't
// connected your source into the output in addition to using the GainNode.
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
mute.id = "activated";
mute.textContent = "Unmute";
} else {
gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
mute.id = "";
mute.textContent = "Mute";
}
};
规范
| 规范 |
|---|
| Web Audio API # dom-baseaudiocontext-creategain |
浏览器兼容性
加载中…