Last active
May 28, 2020 23:22
-
-
Save charlieroberts/7bcc6e19c66b9ed2b4bf26db309738e4 to your computer and use it in GitHub Desktop.
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
<!-- | |
This file demonstrates how to create an audiocontext and AudioWorklet node to use with genish.js. | |
If AudioWorklet is unavailable (for example, in Safari) a ScriptProcessor node will be used. | |
Most of the code consists of setup; the synthesis (a FM synthesized gong) is only six lines of code. | |
--> | |
<!doctype html> | |
<html lang='en'> | |
<head> | |
<meta charset='utf-8'> | |
<title>genish.js AudioWorklet FM demo</title> | |
<script src='http://www.charlie-roberts.com/genish/dist/gen.lib.js'></script> | |
</head> | |
<body></body> | |
<script> | |
// need to wait for the genish.js file to be loaded... | |
window.onload = function() { | |
// put genish functions in global namespace... | |
// you certainly don't have to do this! If you don't, every genish.js | |
// ugen needs to reference the genish object (so, genish.cycle, genish.mul etc.) | |
genish.export( window ) | |
const baseFrequency = 80, c2m = 1.4, index = .95 | |
// create our oscillator for modulation | |
let modulator = cycle( mul( baseFrequency, c2m ) ) | |
// create an envelope lasting eight seconds | |
// this envelope will control both the overall amplitude | |
// of the gong as well as the brightness of the timbre by | |
// modulating its index property. we will also call its | |
// trigger() method to trigger/re-trigger the gong. | |
const env = ad( 44, gen.samplerate * 8 ) | |
// scale amplitude based on index value, re-assign | |
modulator = mul( modulator, mul( baseFrequency, mul( index, env ) ) ) | |
// create carrier oscillator and modulate frequency | |
const carrier = cycle( add( baseFrequency, modulator ) ) | |
// make our audio context with a buffer size of 2048 samples. | |
// because browsers require user interaction to trigger audio | |
// this adds callback functions that will be called when the user first | |
// clicks/touches/presses a key in the browser window; the context is | |
// created then. | |
utilities.createContext( 2048 ) | |
// make worklet only the first time window is clicked | |
// and trigger gong every time window is clicked | |
let init = false | |
window.onclick = ()=> { | |
if( init === false ) { | |
utilities.playWorklet( mul( carrier, env ), 'fmsynth', true ) | |
init = true | |
} | |
env.trigger() | |
} | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment