Last active
October 7, 2018 23:12
-
-
Save aamnah/efd400ac8b0ff0af84a4e438e02336a6 to your computer and use it in GitHub Desktop.
Web Audio API - Create a sound in browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create an Audio Context | |
let context = new AudioContext() | |
// Create an Oscillator | |
let osc = context.createOscillator() | |
// Lower the volume | |
/* | |
.createGain() represents a change in Volume | |
It's an `AudioNode` audio-processing module that causes a given 'gain' | |
to be applied to the input data before it's propagation to the output | |
*/ | |
let volume = context.createGain() | |
volume.gain.value = 0.5 // volume will be multiplied by this value | |
// Connect all nodes | |
osc.connect(volume) | |
// Connect the Gain node (volume) to Speakers | |
/* | |
context.destination is the final output of your sound | |
e.g. Speakers | |
*/ | |
volume.connect(context.destination) | |
// start the oscillator sound | |
osc.start() | |
// stop the oscillator sound | |
osc.stop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let context = new AudioContext(), // create `BaseAudioContext` | |
osc = context.createOscillator(), // create an `OscillatorNode` | |
volume = context.createGain() // create `GainNode` | |
volume.gain.value = 0.5 // the `GainNode` takes an `AudioParam` | |
/* | |
AudioNode.connect() let's you connect one of the node's outputs to a target | |
GainNode and OscillatorNode are both an AudioNode, so both can use .connect() | |
*/ | |
// connect the osc to volume node | |
osc.connect(volume) | |
/* | |
`destination` is a property of BaseAudioContext, represents the final destination of all audio in the context. It usually means your device's speakers | |
*/ | |
// connect volume to speakers | |
volume.connect(context.destination) | |
/* | |
.start() and .stop() are methods of an OscillatorNode | |
*/ | |
osc.start(context.currentTime) | |
osc.stop(context.currentTime + 1) // stop the oscillator after a second |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment