Skip to content

Instantly share code, notes, and snippets.

@Xenakios
Created February 8, 2021 19:46
Show Gist options
  • Save Xenakios/118d3c86e5664f0310ef5a6106caa9e6 to your computer and use it in GitHub Desktop.
Save Xenakios/118d3c86e5664f0310ef5a6106caa9e6 to your computer and use it in GitHub Desktop.
#include <vector>
#include <functional>
class ImgWaveOscillator
{
public:
void initialise(std::function<float(float)> f,
int tablesize)
{
m_tablesize = tablesize;
m_table.resize(tablesize);
for (int i=0;i<tablesize;++i)
m_table[i] = f(rescale(i,0,tablesize-1,-g_pi,g_pi));
}
void setFrequency(float hz)
{
m_phaseincrement = m_tablesize*hz*(1.0/m_sr);
m_freq = hz;
}
float getFrequency()
{
return m_freq;
}
float processSample(float)
{
int index0 = std::floor(m_phase);
int index1 = std::floor(m_phase)+1;
if (index1>=m_tablesize)
index1 = 0;
float frac = m_phase-index0;
float y0 = m_table[index0];
float y1 = m_table[index1];
float sample = y0+(y1-y0)*frac;
m_phase+=m_phaseincrement;
if (m_phase>=m_tablesize)
m_phase-=m_tablesize;
return sample;
}
void prepare(int numchans, float sr)
{
m_sr = sr;
setFrequency(m_freq);
}
void reset(float initphase)
{
m_phase = initphase;
}
void setTable(std::vector<float> tb)
{
m_tablesize = tb.size();
m_table = tb;
}
private:
int m_tablesize = 0;
std::vector<float> m_table;
double m_phase = 0.0;
float m_sr = 44100.0f;
float m_phaseincrement = 0.0f;
float m_freq = 440.0f;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment