Skip to content

Instantly share code, notes, and snippets.

@ChausseBenjamin
Last active January 16, 2023 02:19
Show Gist options
  • Save ChausseBenjamin/e550977c22af43f9b9ee61f4772aca3b to your computer and use it in GitHub Desktop.
Save ChausseBenjamin/e550977c22af43f9b9ee61f4772aca3b to your computer and use it in GitHub Desktop.
converts a note (as a string) to a frequency in hertz
#include "note.h"
#include <math.h>
#include <algorithm>
// note string structure:
// [A-G][0-9][f,n,s]
// A-G: Note entre La (A) et Sol (G)
// 0-9: Octave du piano
// f: bémol (flat), n: naturel, s: dièse (sharp)
// Donc "D3s" va jour le troisième Ré dièse du piano
// list of notes and list of their corresponding frequencies
string note_names[] = {
"A", "A#", "B", "C",
"C#", "D", "D#", "E",
"F", "F#", "G", "G#"
};
float note_hertz[] = {
440.0, 466.16, 493.88, 523.25,
554.37, 587.33, 622.25, 659.25,
698.46, 739.99, 783.99, 830.61
};
float Note::getHertz(){
// calculate the frequency of the note in hertz
// based on the note string.
// The tuning is A4 = 440 Hz, equal temperament
// get the note modifier (sharp, flat, natural)
char modifier = note[note.length()-1];
int offset;
switch (modifier) {
case 's': offset = 1; break;
case 'f': offset = -1; break;
case 'n': offset = 0; break;
default: offset = 0;
}
// get the octave value
int octave = note[note.length()-2] - '0';
octave -= 4;
// Get the first character of the note string
string note_name = note.substr(0, 1);
// Find the note in the note_names array and adjust the offset
int index = find(note_names, note_names + 12, note_name) - note_names + offset;
// if the note index is below 0, lower the octave by 1 and add 12 to the index
// if the note index is above 11, raise the octave by 1 and subtract 12 from the index
switch (index) {
case -1: octave--; index = 11; break;
case 12: octave++; index = 0; break;
};
// calculate the frequency of the note
// based on the note index and the octave
float hertz = note_hertz[index] * pow(2, octave);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment