Factored out scale code

This commit is contained in:
yaw-man 2022-09-19 17:32:24 -04:00
parent f4eb2bdfaf
commit 4e3fa9f24d
1 changed files with 21 additions and 21 deletions

View File

@ -4,13 +4,6 @@
#include <vector>
#include <string>
struct Note
{
std::string name;
double hz;
unsigned int number;
};
static std::vector<std::string> defaultNoteNames = {
"A",
"A#",
@ -46,17 +39,20 @@ public:
// Default ctor: 12TET @ 48kHz
Scale(double hz = 440.0)
{
hz /= 64.0;
hz /= 32.0;
for (int i = 0; i < 12 * 8; ++i)
for (int oct = 0; oct < 8; ++oct)
{
frequencies.push_back(hz);
periods.push_back(sampleRate / hz);
names.push_back(defaultNoteNames[i % 12]);
hz *= exp2(1.0 / 12.0);
}
}
for (int j = 0; j < 12; ++j)
{
double note = exp2(j / 12.0) * hz * (1 << oct);
frequencies.push_back(note);
periods.push_back(sampleRate / note);
names.push_back(defaultNoteNames[j]);
}
}
}
double getNearestPeriod(double period)
{
@ -70,21 +66,27 @@ public:
return 0;
}
unsigned int getNearestNoteNumber(double hz)
double getNearestNoteNumber(double hz)
{
for ( unsigned int i = 0; i < frequencies.size(); ++i )
for (unsigned int i = 0; i < frequencies.size(); ++i)
{
if (hz < frequencies[i]) return i;
if (hz < frequencies[i])
{
if (i == 0)
return i;
return 1.0 * i + (hz - frequencies[i - 1]) / (frequencies[i] - frequencies[i - 1]);
}
}
return 0;
return 0.0;
}
double getNearestFrequency(double hz)
{
for (auto note : frequencies)
{
if (hz < note) return note;
if (hz < note)
return note;
}
return 0;
@ -93,6 +95,4 @@ public:
// TODO: parse scala files. new ctor that parses arbitrary scales
};
#endif