如何改变振荡器频率?

How to change oscillator frequency?

我开始尝试使用 Web Audio API,尝试创建不同的振荡器来产生声波。

由于我对整个过程有点陌生,我想知道是否有一种方法可以播放音调,不是以恒定的频率,而是在中途改变它们。

示例: 我想要一个音调,从 300 Hz 开始,持续 3 秒,然后 线性提升 400 Hz 接下来 4 秒

我找到了这个,但我不确定它是否是我要找的:

osc.setPeriodicWave(wave);

我的 JavaScript 到目前为止:

$(document).ready(function() {

// Function that plays the tone.
var playTone = function(duration, frequency) {
var context = new(window.AudioContext || window.webkitAudioContext)();
var osc = context.createOscillator(); 
// Sine is the default type. Also available: square, sawtooth and triangle waveforms.
osc.type = 'sine'; 
// Frequency in Hz.
osc.frequency.value = frequency; // Frequency in Hz
osc.connect(context.destination); 
osc.start(context.currentTime);
osc.stop(context.currentTime + duration);
}

// Button and input functionality.
$("button").on("click", function() {

var whichButton = $(this).text()
var duration = document.getElementById("durationInput").value;
var frequency = document.getElementById("f1Input").value;
if (whichButton == "  Play") {
  playTone(duration, frequency); 
}

});

});

到目前为止我的代码笔: Codepen.io - Acoustic wave generator

您不需要 PeriodicWave - 它用于谐波(加法)合成。

这非常简单 - 您只需要使用频率 AudioParam 的调度方法 "setValueAtTime" 和 "linearRampToValueAtTime"。试试这个:

// Function that plays the tone.
var playTone = function(duration, frequency) {
    var context = new(window.AudioContext || window.webkitAudioContext)();
    var osc = context.createOscillator(); 
    // Sine is the default type. Also available: square, sawtooth and triangle waveforms.
    osc.type = 'sine'; 
    var now = context.currentTime;
    // Frequency in Hz.
    // Set initial value. (you can use .value=freq if you want)
    osc.frequency.setValueAtTime(frequency, now);
    // set a "checkpoint" in 3 seconds - that will be the starting point of the ramp.
    osc.frequency.setValueAtTime(frequency, now+3);
    // set a ramp to freq+100Hz over the next 4 seconds.
    osc.frequency.linearRampToValueAtTime(frequency+100,now+7)
    osc.connect(context.destination); 
    osc.start(now);
    osc.stop(now + duration);
}