genish.js
Version:
68 lines (56 loc) • 2.3 kB
HTML
<!--
This file demonstrates how to create an audiocontext and audioworklet node to use with genish.js.
Most of the code consists of setup; the synthesis (a FM synthesized gong) is only six lines of code.
-->
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>genish.js AudioWorklet FM demo</title>
<script src='../dist/gen.lib.js'></script>
</head>
<body>
<p style="width:25em;" >
<span style="font-weight:bold">Click/touch in the page to begin</span>.
This example shows how to build a simple FM synth playing a gong sound in genish.js.
If you open your developer's console, you should see the generated callback function.
</p>
</body>
<script>
// need to wait for the genish.js library 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.
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.
utilities.createContext( 2048 )
const synth = mul( carrier, env )
// 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( synth, 'fmsynth', true )
init = true
}
env.trigger()
}
}
</script>
</html>