Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SineWaveGenerator
/**
* @brief Generates a Sound with the help of sin() function.
* @author Phil Schatzmann
* @copyright GPLv3
*
*/
template <class T>
class SineWaveGenerator {
public:
// the scale defines the max value which is generated
SineWaveGenerator(float amplitude = 32767.0, float phase = 0) {
m_amplitude = amplitude;
m_phase = phase;
}
/// Starts the processing by defining the sample rate and frequency
void begin(uint16_t sample_rate=44100, uint16_t frequency=0){
this->m_frequency = frequency;
this->m_sample_rate = sample_rate;
this->m_deltaTime = 1.0 / m_sample_rate;
}
/// Defines the frequency - after the processing has been started
void setFrequency(uint16_t frequency) {
this->m_frequency = frequency;
}
/// Provides a single sample
virtual T readSample() {
float angle = double_Pi * m_frequency * m_time + m_phase;
T result = m_amplitude * sin(angle);
m_time += m_deltaTime;
return result;
}
protected:
uint16_t m_sample_rate;
float m_frequency = 0;
float m_time = 0.0;
float m_amplitude = 1.0;
float m_deltaTime = 1.0 / m_sample_rate;
float m_phase = 0.0;
float double_Pi = PI * 2.0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment