Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting frequency (Hz) to notes and back #34

Open
Bauxitedev opened this issue May 28, 2021 · 3 comments
Open

Converting frequency (Hz) to notes and back #34

Bauxitedev opened this issue May 28, 2021 · 3 comments

Comments

@Bauxitedev
Copy link

Bauxitedev commented May 28, 2021

I was just wondering, is it possible to convert a frequency in Hertz to the nearest note, and vice versa? If not, how would I go about doing this?

@XBagon
Copy link
Contributor

XBagon commented Jun 1, 2021

I think this would require some general work on tunings to be implemented properly.
For now something like this should work (assuming A4 to be 440Hz):

fn note_nr(note: Note) -> u8 {
    note.pitch_class.into_u8() + 12 * note.octave
}

fn note_to_freq(note: Note) -> f32 {
    let a440 = note_nr(Note::new(PitchClass::A, 4));
    2f32.powf(((note_nr(note) as i16 - a440 as i16) as f32) / 12.0) * 440.0
}

fn from_note_nr(nr: u8) -> Note {
    println!("nr: {}", nr);
    let pitch_class = PitchClass::from_u8(nr % 12);
    let octave = nr / 12;
    Note::new(pitch_class, octave)
}

fn freq_to_note(freq: f32) -> Note {
    let a440 = note_nr(Note::new(PitchClass::A, 4));
    from_note_nr(((12.0 * (freq/440.0).log2()) as i16 + a440 as i16) as u8)
}

@the-drunk-coder
Copy link

I was just about to ask this, it'd come in handy. A music library that can do these conversions (like music21 in Python or CommonMusic2 in CommonLisp) is still missing in Rust, as far as I know.

@the-drunk-coder
Copy link

I added the feature as described above to my fork ... not sure if a PR is warranted ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants