JSFiddle - React, Tailwind, and code Playground
JavaScript
var audioCtx = new ( window.AudioContext || window.webkitAudioContext() );
snd1( audioCtx );
snd2( audioCtx );
snd2( audioCtx, { delay: 1 } );
window.setTimeout( () => snd2( audioCtx ), 2000 );
function snd1( ctx, options = {} ) {
let oscNode = ctx.createOscillator();
let gainNode = ctx.createGain();
let now = ctx.currentTime + options.delay || 0;
let duration = 0.200;
// set frequency and type
oscNode.frequency.value = 370;
// oscNode.frequency.cancelScheduledValues( now );
oscNode.frequency.setValueAtTime( oscNode.frequency.value, now );
// oscNode.frequency.linearRampToValueAtTime( 350, now + duration/3 );
oscNode.frequency.linearRampToValueAtTime( 450, now + duration );
oscNode.type = 'triangle';
// set gain
gainNode.gain.value = 0.35;
gainNode.gain.setValueAtTime( gainNode.gain.value, now );
gainNode.gain.exponentialRampToValueAtTime( 0.01, 7*duration/8 );
oscNode.connect( gainNode );
gainNode.connect( ctx.destination );
oscNode.start(now);
oscNode.stop(duration);
};
function snd2( ctx, options = {} ) {
console.log(ctx);
let oscNode = ctx.createOscillator();
let gainNode = ctx.createGain();
let now = ctx.currentTime + options.delay || 0;
let duration = 0.200;
// set frequency and type
oscNode.frequency.value = 370;
// oscNode.frequency.cancelScheduledValues( now );
oscNode.frequency.setValueAtTime( oscNode.frequency.value, now );
// oscNode.frequency.linearRampToValueAtTime( 350, now + duration/3 );
oscNode.frequency.linearRampToValueAtTime( 300, now + duration );
oscNode.type = 'triangle';
// set gain
gainNode.gain.value = 0.35;
gainNode.gain.setValueAtTime( gainNode.gain.value, now );
gainNode.gain.exponentialRampToValueAtTime( 0.01, 7*duration/8 );
oscNode.connect( gainNode );
gainNode.connect( ctx.destination );
oscNode.start(now);
oscNode.stop(duration);
};