抖音开放平台Logo
控制台

AudioContext.createGain
收藏
我的收藏

基础库 1.34.0 开始支持本方法,这是一个同步方法。

创建并返回一个新的 GainNode 对象实例,GainNode 是一个 AudioNode 音频处理模块,在输出前使用给定增益应用到输入。

前提条件
业务背景
使用限制
注意事项
相关教程

语法

AudioContext.createGain()

参数说明

返回值

类型说明最低支持版本
object

GainNode 对象实例

1.34.0

代码示例

// 1. 创建一个 AudioContext 和 Audio
const ctx = tt.getAudioContext();
const audio = ctx.createAudio();
audio.src = "xxxx.mp3";
// 2. 创建一个长度为 3s 的正弦波形
const buf = ctx.createBuffer(2, ctx.sampleRate * 3, ctx.sampleRate);
for (let channel = 0; channel < buf.numberOfChannels; channel++) {
  // This gives us the actual array that contains the data
  const arr = buf.getChannelData(channel);
  for (let i = 0; i < buf.length; i++) {
    // 限制峰值,防止混声溢出
    arr[i] = Math.sin((i / ctx.sampleRate) * 400 * Math.PI * 2) * 0.6;
  }
}
const source = ctx.createBufferSource();
source.buffer = buf;

// 创建增益中间节点,并且初始值为0
const gainNode = ctx.createGain();
gainNode.gain.value = 0;
source.connect(gainNode);
gainNode.connect(ctx.destination);

source.start();
source.onended = function () {
  console.log("onended called", this);
};