diff --git a/src/formatters.rs b/src/formatters.rs index 08bebd7e..e4989731 100644 --- a/src/formatters.rs +++ b/src/formatters.rs @@ -143,7 +143,7 @@ pub fn v2s_f32_hz_then_khz_with_note_name( ) -> Arc String + Send + Sync> { Arc::new(move |value| { // This is the inverse of the formula in `f32_midi_note_to_freq` - let fractional_note = ((value / 440.0).log2() * 12.0) + 69.0; + let fractional_note = util::freq_to_midi_note(value); let note = fractional_note.round(); let cents = ((fractional_note - note) * 100.0) as i32; diff --git a/src/util.rs b/src/util.rs index 173464a8..8e5c772e 100644 --- a/src/util.rs +++ b/src/util.rs @@ -57,6 +57,13 @@ pub fn f32_midi_note_to_freq(note: f32) -> f32 { 2.0f32.powf((note - 69.0) / 12.0) * 440.0 } +/// The inverse of [`f32_midi_note_to_freq()`]. This returns a fractional note number. Round to a +/// whole number, subtract that from the result, and multiply the fractional part by 100 to get the +/// number of cents. +pub fn freq_to_midi_note(freq: f32) -> f32 { + ((freq / 440.0).log2() * 12.0) + 69.0 +} + #[cfg(test)] mod tests { use super::*;