本文介绍了如何改变振荡器频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I started to experiment with the Web Audio API, trying to create different oscillators to produce acoustic waves.

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

Since I'm kinda new to the whole process, I'm wondering if there's a way to play tones, not with a constant frequency, but changing them midways.

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

Example:I want a tone, that starts at 300 Hz for 3 seconds, and then raise linearly to 400 Hz over the next 4 seconds.

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

I fount this, but I'm not really sure if it is what I'm looking for:

osc.setPeriodicWave(wave);

到目前为止我的 JavaScript:

My JavaScript so far:

$(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- 声波发生器

推荐答案

您不需要 PeriodicWave - 那是用于谐波(加法)合成的.

You don't want a PeriodicWave - that's for harmonic (additive) synthesis.

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

This is pretty straightforward - you just need to use the frequency AudioParam's scheduling methods "setValueAtTime" and "linearRampToValueAtTime". Try this:

// 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);
}

这篇关于如何改变振荡器频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 15:39