Web Audio Oscillator

by amindunited

HTML

<button>
HitMe
</button>

JavaScript

const frequency = (noteNumber) => {
		// The 40th note is middle C
    // the frequency of the noteNumber 
    var n = noteNumber - 40;
    console.log("in frequency .... noteNumber", n / 12);
    freq = Math.pow(2, n/12) * 440;
    console.log('freq', freq, "should be 440");
    return freq;
};

const webAudioContext = new AudioContext();

class Note {
	attack = 1;
  decay = 1;
  sustain = 1;
  release = 1;
  oscillator;
  gainNode;
  
	start () {

		this.gainNode = webAudioContext.createGain();
	  this.gainNode.connect(webAudioContext.destination);
		this.gainNode.gain.value = 0;// 1;

		this.oscillator = webAudioContext.createOscillator();
    this.oscillator.connect(this.gainNode);    

    this.oscillator.type = 'triangle';
		this.oscillator.frequency.value = frequency(28); // The 40th note is middle C

		this.oscillator.start(webAudioContext.currentTime);
    const totalTime = webAudioContext.currentTime
    	+ this.attack
      + this.decay
      + this.sustain
      + this.release;
    this.oscillator.stop(totalTime);

    // const waveArray = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0];
    // this.gainNode.gain.setValueCurveAtTime(waveArray, webAudioContext.currentTime, webAudioContext.currentTime + 4);

    // const waveArray = [0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0];
    // this.gainNode.gain.setValueCurveAtTime(waveArray, webAudioContext.currentTime, webAudioContext.currentTime + 4);
    
    // this.gainNode.gain.exponentialRampToValueAtTime(0.01, webAudioContext.currentTime + 1)
    /*
    const waveArray = new Float32Array(9);
      waveArray[0] = 0.5;
      waveArray[1] = 1;
      waveArray[2] = 0.5;
      waveArray[3] = 0;
      waveArray[4] = 0.5;
      waveArray[5] = 0.3;
      waveArray[6] = 0.2;
      waveArray[7] = 0.1;
      waveArray[8] = 0;
    this.gainNode.gain.setValueCurveAtTime(waveArray, webAudioContext.currentTime, 2);
    */
    this.gainNode.gain.linearRampToValueAtTime(
        1,
       ...