2022-09-16 15:38:52 +00:00
|
|
|
#ifndef YAW_SCALE_INCLUDED
|
|
|
|
#define YAW_SCALE_INCLUDED
|
|
|
|
|
|
|
|
#include <vector>
|
2022-09-18 17:50:35 +00:00
|
|
|
#include <string>
|
|
|
|
|
|
|
|
static std::vector<std::string> defaultNoteNames = {
|
|
|
|
"A",
|
|
|
|
"A#",
|
|
|
|
"B",
|
|
|
|
"C",
|
|
|
|
"C#",
|
|
|
|
"D",
|
|
|
|
"D#",
|
|
|
|
"E",
|
|
|
|
"F",
|
|
|
|
"F#",
|
|
|
|
"G",
|
|
|
|
"G#"};
|
2022-09-16 15:38:52 +00:00
|
|
|
|
|
|
|
class Scale
|
|
|
|
{
|
|
|
|
double sampleRate = 48000.0;
|
|
|
|
|
|
|
|
// freqs in hz, periods in samples
|
|
|
|
std::vector<double> frequencies;
|
|
|
|
std::vector<double> periods;
|
2022-09-18 17:50:35 +00:00
|
|
|
std::vector<std::string> names;
|
2022-09-16 15:38:52 +00:00
|
|
|
|
|
|
|
public:
|
|
|
|
void newSampleRate(double rate)
|
|
|
|
{
|
|
|
|
double ratio = rate / sampleRate;
|
|
|
|
sampleRate = rate;
|
|
|
|
for (double ¬e : periods)
|
|
|
|
note *= ratio;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Default ctor: 12TET @ 48kHz
|
|
|
|
Scale(double hz = 440.0)
|
|
|
|
{
|
2022-09-19 21:32:24 +00:00
|
|
|
hz /= 32.0;
|
2022-09-16 15:38:52 +00:00
|
|
|
|
2022-09-19 21:32:24 +00:00
|
|
|
for (int oct = 0; oct < 8; ++oct)
|
2022-09-16 15:38:52 +00:00
|
|
|
{
|
2022-09-19 21:32:24 +00:00
|
|
|
|
|
|
|
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]);
|
|
|
|
}
|
2022-09-16 15:38:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
double getNearestPeriod(double period)
|
|
|
|
{
|
|
|
|
for (auto note : periods)
|
|
|
|
{
|
|
|
|
if (period > note)
|
|
|
|
return note;
|
|
|
|
}
|
|
|
|
|
|
|
|
// This should NOT happen.
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-09-19 21:32:24 +00:00
|
|
|
double getNearestNoteNumber(double hz)
|
2022-09-18 17:50:35 +00:00
|
|
|
{
|
2022-09-19 21:32:24 +00:00
|
|
|
for (unsigned int i = 0; i < frequencies.size(); ++i)
|
2022-09-18 17:50:35 +00:00
|
|
|
{
|
2022-09-19 21:32:24 +00:00
|
|
|
if (hz < frequencies[i])
|
|
|
|
{
|
|
|
|
if (i == 0)
|
|
|
|
return i;
|
|
|
|
return 1.0 * i + (hz - frequencies[i - 1]) / (frequencies[i] - frequencies[i - 1]);
|
|
|
|
}
|
2022-09-18 17:50:35 +00:00
|
|
|
}
|
|
|
|
|
2022-09-19 21:32:24 +00:00
|
|
|
return 0.0;
|
2022-09-18 17:50:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
double getNearestFrequency(double hz)
|
|
|
|
{
|
|
|
|
for (auto note : frequencies)
|
|
|
|
{
|
2022-09-19 21:32:24 +00:00
|
|
|
if (hz < note)
|
|
|
|
return note;
|
2022-09-18 17:50:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-09-16 15:38:52 +00:00
|
|
|
// TODO: parse scala files. new ctor that parses arbitrary scales
|
|
|
|
};
|
|
|
|
|
|
|
|
#endif
|