wavetable-synth/src/synthesizer.rs

53 lines
1.4 KiB
Rust

use crate::wavetable::Wavetable;
pub trait Synthesizer {}
pub struct SimpleWavetableSynthesizer<W: Wavetable> {
wavetable: W,
clock_freq_hz: usize,
output_freq_hz: usize,
enable: bool,
counter: usize,
clock_per_sample: usize,
current_output: <W as Wavetable>::OutputType,
output_flag: bool,
}
impl<W: Wavetable> SimpleWavetableSynthesizer<W> {
pub fn new(wavetable: W, clock_freq_hz: usize) -> Self {
Self {
wavetable,
clock_freq_hz,
output_freq_hz: 1,
enable: false,
counter: 0,
clock_per_sample: 0,
current_output: <W as Wavetable>::OutputType::default(),
output_flag: false,
}
}
pub fn has_new_output(&self) -> bool {
self.output_flag
}
pub fn get_output(&mut self) -> <W as Wavetable>::OutputType {
self.output_flag = false;
self.current_output
}
pub fn set_freq(&mut self, freq_hz: usize) {
self.output_freq_hz = freq_hz;
// probably a better way to do this with modulos or something...
self.clock_per_sample = self.clock_freq_hz / self.output_freq_hz / self.wavetable.size();
}
pub fn tick(&mut self) {
if self.counter == self.clock_per_sample {
self.counter = 0;
self.current_output = self.wavetable.next();
self.output_flag = true;
}
self.counter += 1;
}
}