simple-synth/single-voice-synth.js

81 lines
2.1 KiB
JavaScript

class Synth {
constructor(audioContext, waveType = "triangle", frequency = 100) {
this.audioContext = audioContext;
this.oscWaveType = waveType;
this.oscFrequency = frequency;
this.isPlaying = false;
// osc setup
this.osc = this.audioContext.createOscillator();
this.osc.type = this.oscWaveType;
this.osc.frequency.setValueAtTime(this.oscFrequency, this.audioContext.currentTime);
this.osc.connect(this.audioContext.destination);
}
setOscWaveType(type) {
this.oscWaveType = type;
this.osc.type = this.oscWaveType;
}
setOscFrequency(freq) {
this.oscFrequency = freq;
this.osc.frequency.setValueAtTime(freq, this.audioContext.currentTime);
}
setOscDetune(amount) {
this.osc.detune.setValueAtTime(amount, this.audioContext.currentTime);
}
startOsc() {
this.osc.start();
this.isPlaying = true;
}
stopOsc() {
// first get all the parameters for this osc
let currentFreq = this.osc.frequency.value;
let currentType = this.osc.type;
this.osc.stop();
this.osc = this.audioContext.createOscillator();
this.osc.type = currentType;
this.osc.frequency.setValueAtTime(currentFreq, this.audioContext.currentTime);
this.osc.connect(this.audioContext.destination);
this.isPlaying = false;
}
toggleOsc() {
if (this.isPlaying === false) {
this.startOsc();
} else {
this.stopOsc();
}
}
}
let globalAudioContext = new AudioContext();
let synth = new Synth(globalAudioContext);
function toggleOscillator() {
synth.toggleOsc();
}
window.onload = function() {
console.log("hello world!");
console.log(synth);
var selectedWaveType = document.querySelector("input[name='wave']");
selectedWaveType.addEventListener("change", () => {
let selectedWaveTypeValue = document.querySelector("input[name='wave']:checked").value;
console.log("the value of the wave has changed to" + selectedWaveTypeValue);
synth.setOscWaveType(selectedWaveTypeValue);
})
var detune = document.getElementById("detune");
detune.addEventListener("input", () => {
synth.setOscDetune(parseFloat(detune.value))
})
}