use rustysynth::Synthesizer; use rustysynth::SoundFont; use rustysynth::SynthesizerSettings; use std::sync::Arc; use crate::tone; pub enum Syn { Real(Synthesizer), Text{ m: std::collections::HashMap>, i: u32, }, } impl Syn { pub fn new(debug: bool, sound_font: String, sample_rate: usize) -> Syn { match debug { false => Syn::new_real(sound_font, sample_rate), true => Syn::Text{m: std::collections::HashMap::new(), i: 0}, } } fn new_real(sound_font: String, sample_rate: usize) -> Syn { let mut sf2 = std::fs::File::open(sound_font).unwrap(); let sound_font = Arc::new(SoundFont::new(&mut sf2).unwrap()); let settings = SynthesizerSettings::new(sample_rate as i32); let synthesizer = Synthesizer::new(&sound_font, &settings).unwrap(); Syn::Real(synthesizer) } pub fn set(&mut self, ch: i32, b: Option) { match self { // channel=[0..16) // velocity=[0..128) Syn::Real(syn) => { syn.note_off_all_channel(ch, false); }, Syn::Text{m, ..} => { m.remove(&ch); }, }; if let Some(tone) = b { self.tone_on(ch, tone); }; } fn tone_on(&mut self, ch: i32, b: tone::Tone) { match self { // channel=[0..16) // velocity=[0..128) Syn::Real(syn) => syn.note_on(ch, b.i32(), 127), Syn::Text{m, ..} => { match m.get_mut(&ch) { Some(m2) => { m2.insert(b.i32(), 127); }, None => { let mut m2 = std::collections::HashMap::new(); m2.insert(b.i32(), 127); m.insert(ch, m2); }, }; }, }; } fn tone_off(&mut self, ch: i32, b: tone::Tone) { match self { Syn::Real(syn) => syn.note_off(ch, b.i32()), Syn::Text{m, ..} => { match m.get_mut(&ch) { Some(m) => { m.remove(&b.i32()); }, None => {}, }; }, }; } pub fn render(&mut self, a: &mut [f32], b: &mut [f32]) { match self { Syn::Real(syn) => syn.render(a, b), Syn::Text{m, i} => { eprintln!("{} | render[{}]({:?})", chrono::prelude::Utc::now(), i, m); *i += 1; }, }; } } #[cfg(test)] mod test { use super::*; #[test] fn test_new_real() { let mut syn = Syn::new(false, "super_small_font.sf2".to_string(), 44100); syn.tone_on(0, tone::new("c")); syn.tone_on(0, tone::new("d")); syn.tone_off(0, tone::new("d")); let mut buffer1 = Vec::::new(); let mut buffer2 = Vec::::new(); syn.render(&mut buffer1, &mut buffer2); } #[test] fn test_text() { let mut syn = Syn::new(true, ".sf2".to_string(), 1); syn.tone_on(0, tone::new("c")); syn.tone_on(0, tone::new("d")); syn.tone_off(0, tone::new("d")); let mut buffer1 = Vec::::new(); let mut buffer2 = Vec::::new(); syn.render(&mut buffer1, &mut buffer2); } }