抖音开放平台Logo
控制台

AudioContext.createBuffer
收藏
我的收藏

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

新建一个空白的 AudioBuffer 对象,以便用于填充数据,通过 AudioBufferSourceNode 播放。

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

语法

AudioContext.createBuffer(channels, length, sampleRate)

参数说明

channels

类型默认值必填说明最低支持版本
number

一个定义了 buffer 中包含的声频通道数量的整数

1.34.0

length

类型默认值必填说明最低支持版本
number

一个代表 buffer 中的样本帧数的整数

1.34.0

sampleRate

类型默认值必填说明最低支持版本
number

线性音频样本的采样率,即每一秒包含的关键帧的个数。可以设置为 44100 或者 22050

1.34.0

返回值

类型说明最低支持版本
object

AudioBuffer 对象实例

1.34.0

代码示例

// 1. 创建一个 AudioContext
const ctx = tt.getAudioContext();

// 2. 创建一个长度为 3s 的正弦波形
const buf = ctx.createBuffer(2, ctx.sampleRate * 3, ctx.sampleRate);
for (let channel = 0; channel < buf.numberOfChannels; channel++) {
  // 获取频道的数据
  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;
source.connect(ctx.destination);

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