Skip to content

Instantly share code, notes, and snippets.

@ekozhura
Last active August 6, 2018 20:28
Show Gist options
  • Save ekozhura/80d7c3782edd7c919a65afbad745a9df to your computer and use it in GitHub Desktop.
Save ekozhura/80d7c3782edd7c919a65afbad745a9df to your computer and use it in GitHub Desktop.
WebAudio Reason bindings (playground)
module AudioNode = {
type audio_node;
};
module AudioParam = {
type audio_param;
[@bs.send] external setValue: audio_param => float => float => unit = "setValueAtTime";
};
module AudioSourceNode = {
include AudioNode;
[@bs.send] external start: audio_node => float => unit = "start";
[@bs.send] external stop: audio_node => float => unit = "stop";
};
module OscillatorNode = {
include AudioSourceNode;
[@bs.get] external freq : audio_node => AudioParam.audio_param = "frequency";
};
[@bs.deriving abstract]
type audio_context_options = {
sampleRate: int
};
type destination = AudioNode.audio_node;
[@bs.deriving abstract]
type audio_context = {
baseLatency: float,
currentTime: float,
sampleRate: float,
destination: destination
};
[@bs.new] external _make: option(audio_context_options) => audio_context = "window.AudioContext";
[@bs.new] external createOsc: (audio_context) => AudioSourceNode.audio_node = "window.OscillatorNode";
[@bs.new] external createAmp: audio_context => AudioNode.audio_node = "window.GainNode";
[@bs.send] external connect: AudioNode.audio_node => AudioNode.audio_node => AudioNode.audio_node = "connect";
let make = (~options) => _make(options);
let start = AudioSourceNode.start;
let stop = AudioSourceNode.stop;
let freq = OscillatorNode.freq;
let setValue = AudioParam.setValue;
open Audio;
let audioCtx = make(~options=None);
let dest = audioCtx|.destinationGet;
let currentTime: float = audioCtx|.currentTimeGet;
let osc = createOsc(audioCtx);
let amp = createAmp(audioCtx);
osc
|. connect(amp)
|. connect(dest);
/* interesting how these two lines, which basically do the same thing, are compiled into different js code */
osc |> OscillatorNode.freq |. AudioParam.setValue(220.0, (currentTime +. 2.5));
osc |> freq |. setValue(330., currentTime +. 3.5);
osc|.start(0.5);
osc|.stop(4.0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment