16.3 Web Audio API(网页音频接口) 运行振荡器

这一节,让我们试着制造一些声音,我们将需要完成以下任务:

  • 创建Web Audio API context
  • 在context中创振荡器节点
  • 选择波形类型
  • 设定频率
  • 把振荡器连接到目标上
  • 启动振荡器
  • 让我们把这些步骤写成代码

var context = new (window.AudioContext || window.webkitAudioContext)();

var oscillator = context.createOscillator();

oscillator.type = 'sine';
oscillator.frequency.value = 440;
oscillator.connect(context.destination);
oscillator.start();

注意我们在定义Audio Context的时候如果是Safari浏览器的话我们需要使用"WebKit"前缀名,所以我们要让它有跨浏览器兼容的能力。

然后我们创建振荡器并设置波形类型(默认类型的值是正弦的,你可以跳过这行。在这里为了使其更清晰,所以添加了它)。我们设定的频率值为440(A4音符,这也是默认值)。音符C0到B8的频率范围在16.35到7902.13HZ。在本章节后面我们会通过一个例子来播放很多不同的音符。

现在我们来学习如何调节音量。我们需要在Audio Context中创建增益节点并把它连接到整个音频链中,并把这个增益节点连接到目标对象中去。

var gain = context.createGain();
oscillator.connect(gain);
gain.connect(context.destination);

var now = context.currentTime;
gain.gain.setValueAtTime(1, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.5);
oscillator.start(now);
oscillator.stop(now + 0.5);

您可以在线试试看: