有没有办法在每次单击按钮时从头开始重新启动 Web Audio API 振荡器?

问题描述 投票:0回答:1

我正在通过使用 Web Audio API 构建一个底鼓合成器。我已经管理我的按钮来运行一个函数,该函数生成具有音调和增益扫描的正弦波,但该按钮似乎只工作一次,并且当再次单击时,它不会从头开始播放声音。

const audioCtx = new AudioContext(); // Initiate Audio Context
const osc = audioCtx.createOscillator(); // Create An Oscillator
const volume = audioCtx.createGain(); // Create A Gain



osc.type = "sine"; // Set the type of the waveform
osc.frequency.value = 440; // Set the frequency value of the oscillator

osc.start(); // Start playing the oscillator
osc.connect(volume); // Set the destination of the oscillator  


function generateKick() {
   volume.gain.value = 1;
   osc.frequency.setTargetAtTime(22, 0, 0.1)
   volume.gain.setTargetAtTime(0, audioCtx.currentTime, 0.1);
   volume.connect(audioCtx.destination);
   
}

如何修改我的函数,以便每次单击按钮时它都会从头开始并发出相同的声音?

JSFiddle

我尝试将

osc.start()
函数放入我自己的函数中,但这不起作用,因为
.start()
函数不能被多次调用。

web-audio-api
1个回答
0
投票

我不是网络音频专家,但是使用

setValueAtTime
在每个
setTargetAtTime
之前重置音量和频率似乎可以解决问题(我也将
volume.connect
放在函数之外,所以它只执行一次):

const audioCtx = new AudioContext(); // Initiate Audio Context const osc = audioCtx.createOscillator(); // Create An Oscillator const volume = audioCtx.createGain(); // Create A Gain osc.type = "sine"; // Set the type of the waveform osc.frequency.value = 440; // Set the frequency value of the oscillator osc.start(); // Start playing the oscillator osc.connect(volume); // Set the destination of the oscillator volume.gain.value = 0; volume.connect(audioCtx.destination); function generateKick() { volume.gain.setValueAtTime(1, audioCtx.currentTime); volume.gain.setTargetAtTime(0, audioCtx.currentTime, 0.1); osc.frequency.setValueAtTime(440, audioCtx.currentTime); osc.frequency.setTargetAtTime(22, audioCtx.currentTime, 0.1); }
    
© www.soinside.com 2019 - 2024. All rights reserved.