In the Web Audio API a parameter of an audio node (an AudioParam) can be changed with sample-accurate timing. Each AudioNode object, such as an oscillator node or a gain node, has one or more properties—the frequency value of an oscillator node or the gain value of a gain node—which can be set at specific times, either immediately or in the future.
The AudioContext provides a property called currentTime, which can serve as a reference point for scheduling the value of an AudioParam to change immediately or at a specific time in the future. You can set an AudioParam to change its value at a specific time using its setValueAtTime() method, or to change its value gradually over time with the linearRampToValueAtTime() method. For example, if I have a constant named ctx set to an AudioContext, and in that context I have a variable named osc set as an Oscillator node, and I wish to change its frequency value to 440 Hz exactly one second from now, I could write osc.frequency.setValueAtTime(440., ctx.currentTime+1.);.
In this example, we create our own "instrument" object consisting of an oscillator node and a gain node, and then we schedule notes to be played on that instrument at specific times by setting the frequency of the oscillator node and the gain of the gain node. To do that, we create an array of pitches and an array of volumes, and establish a beat tempo. Then we step through the two arrays, scheduling different pitches and volumes to happen at specific times based on the tempo. The program schedules 64 notes at once, then plays them.
This page was last modified January 21, 2024
by Christopher Dobrian, dobrian@uci.edu