Skip to content

Instantly share code, notes, and snippets.

@Davidslv
Created October 21, 2022 22:59
Show Gist options
  • Save Davidslv/722363e7cac42910778026dbffbb2f35 to your computer and use it in GitHub Desktop.
Save Davidslv/722363e7cac42910778026dbffbb2f35 to your computer and use it in GitHub Desktop.
Playing Sound with Javascript
class SoundMaker {
constructor() {
this.context = new AudioContext();
this.oscillator = new Oscillator(this.context);
this.gain = this.context.createGain();
this.volume = new Volume(this.context, this.gain);
}
start() {
this.oscillator.connect(this.gain);
this.gain.connect(this.context.destination);
this.oscillator.start();
}
setNote(frequency, type) {
this.setFrequency(frequency);
this.setType(type);
}
setFrequency(frequency) { this.oscillator.setFrequency(frequency); }
setType(type) { this.oscillator.setType(type); }
down(x) { this.volume.down(x); }
up(x) { this.volume.up(x); }
mute(mute = true) { this.volume.mute(mute); }
stop() { this.oscillator.stop(); }
}
class Oscillator {
constructor(context) {
this.context = context;
this.oscillator = context.createOscillator();
}
// hertz
setFrequency(frequency = 440.0) {
this.oscillator.frequency.setValueAtTime(frequency, this.context.currentTime);
}
setType(type = "sine") {
const validTypes = ["sine", "square", "sawtooth", "triangle"];
if (!validTypes.includes(type)) return;
this.oscillator.type = type
}
connect(object) {
this.oscillator.connect(object);
}
start() {
this.oscillator.start(0);
}
// destructive, won't be able to start it again
stop() {
this.oscillator.stop();
}
}
class Volume {
constructor(context, gainNode) {
this.gainNode = gainNode
this.gain = gainNode.gain;
this.context = context;
}
mute(mute = true) {
if (mute) {
this.gainNode.disconnect(this.context.destination);
}
else {
this.gainNode.connect(this.context.destination);
}
}
down(x = 1) {
this.gain.exponentialRampToValueAtTime(
0.00001, this.context.currentTime + x
)
}
up(x = 1) {
this.gain.exponentialRampToValueAtTime(
0.5, this.context.currentTime + x
)
}
}
let maker = new SoundMaker();
// make sure you set your volume to low before proceeding
maker.start();
maker.setNote(261.6, "sine");
maker.mute();
maker.mute(false);
maker.setNote(174.6, "square");
maker.setNote(1109, "sawtooth");
maker.setNote(87.31, "triangle")
maker.mute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment