qualia_audio/midi/synth/
voice.rs1use super::adsr::AdsrEnvelope;
8use super::oscillator_voice::{OscillatorVoice, Waveform};
9
10#[derive(Clone, Copy, Debug)]
12pub struct Voice {
13 osc: OscillatorVoice,
14 note: u8,
16 age: u64,
18 held: bool,
20}
21
22impl Voice {
23 pub fn new(sample_rate: f32, waveform: Waveform, env: AdsrEnvelope) -> Self {
25 Self {
26 osc: OscillatorVoice::new(sample_rate, waveform, env),
27 note: 0,
28 age: 0,
29 held: false,
30 }
31 }
32
33 pub fn note_on(&mut self, note: u8, velocity: u8, freq_hz: f32, age: u64) {
35 self.note = note;
36 self.age = age;
37 self.held = true;
38 self.osc.note_on(freq_hz, velocity);
39 }
40
41 pub fn note_off(&mut self) {
43 self.held = false;
44 self.osc.note_off();
45 }
46
47 #[inline]
49 pub fn is_active(&self) -> bool {
50 self.osc.is_active()
51 }
52
53 #[inline]
55 pub fn is_held(&self) -> bool {
56 self.held
57 }
58
59 #[inline]
61 pub fn note(&self) -> u8 {
62 self.note
63 }
64
65 #[inline]
67 pub fn age(&self) -> u64 {
68 self.age
69 }
70
71 #[inline]
73 pub fn render_sample(&mut self) -> f32 {
74 self.osc.render_sample()
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 const SR: f32 = 48_000.0;
83
84 fn env() -> AdsrEnvelope {
85 AdsrEnvelope::new(SR, 0.001, 0.0, 1.0, 0.010)
86 }
87
88 #[test]
89 fn lifecycle_active_and_held_flags() {
90 let mut v = Voice::new(SR, Waveform::Sine, env());
91 assert!(!v.is_active());
92 assert!(!v.is_held());
93
94 v.note_on(60, 100, 261.63, 7);
95 assert!(v.is_active());
96 assert!(v.is_held());
97 assert_eq!(v.note(), 60);
98 assert_eq!(v.age(), 7);
99
100 v.note_off();
101 assert!(v.is_active());
103 assert!(!v.is_held());
104 }
105}