# web audio api

<https://tomhazledine.com/web-audio-delay/>

## HTML

```
<button id="osc">sound</button>
```

## JS 1

```
const context = new AudioContext(); //allows access to web audio api
    
document.querySelector('#osc').addEventListener('click', function () {
    note();
});

function note() {
    var oscillator = context.createOscillator(); //creates oscillator
    oscillator.type = "sawtooth"; //chooses the type of wave
    oscillator.frequency.value = 100; //assigning the value of oscPitch to the oscillators frequency value
 
    oscillator.connect(context.destination); //sends to output 
    oscillator.start(context.currentTime); //starts oscillator
    oscillator.stop(context.currentTime + 1); //stops oscillator
};
```

## JS 2

```
// coming soon
```

## JS more advanced

```
const context = new AudioContext(); //allows access to webaudioapi

 function task(i) {
   setTimeout(function() {
       note();
   }, 1000 * Math.random()*i);
 }

document.querySelector('#osc').addEventListener('click', function () {
    for (let i=0; i<10; i++) {
        task(i);
     }
});

function note() {
    
    const attackTime = 0.4;
    const decayTime = 0.1;
    const sustainLevel = 0.7;
    const sustainTime = 1.0;
    const releaseTime = 2.0;

    const noteGain = context.createGain();
    noteGain.gain.setValueAtTime(0,context.currentTime);
    
    oscillator = context.createOscillator(); //creates oscillator
    oscillator.connect(noteGain);
    noteGain.connect(context.destination); //sends to output
    
    let oscPitch = Math.floor(Math.random()*600) + 20; //assigning the value of the slider to a variable
    
    oscillator.type = "sawtooth"; //chooses the type of wave
    oscillator.frequency.value = oscPitch; //assigning the value of oscPitch to the oscillators frequency value

    oscillator.start(); //starts oscillator
    
    let now = context.currentTime;
    
    noteGain.gain.linearRampToValueAtTime(1, now + attackTime);
    noteGain.gain.linearRampToValueAtTime(sustainLevel, now + attackTime + decayTime);
    noteGain.gain.linearRampToValueAtTime(0, now + attackTime + decayTime + sustainTime + releaseTime);
    
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://benjohansen.gitbook.io/musictech/2023_spring/projects/web-audio-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
