Created
June 15, 2023 20:37
-
-
Save Xenakios/3a3af68f1cb1221cee4c3c23300822d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SampleAccurateTimer | |
{ | |
public: | |
SampleAccurateTimer() {} | |
void setIntervalSamples(int samples) | |
{ | |
m_counter = 0; | |
m_period = samples; | |
} | |
std::function<void(int)> Callback; | |
void advance(int numsamples) | |
{ | |
jassert(m_period > 0); | |
jassert(Callback); // callback must be set | |
// this could be done more elegantly/efficiently, perhaps... | |
// but this brute force approach is simple to understand | |
for (int i = 0; i < numsamples; ++i) | |
{ | |
if (m_counter == 0) | |
{ | |
Callback(i); | |
} | |
++m_counter; | |
if (m_counter == m_period) | |
m_counter = 0; | |
} | |
} | |
void reset() { m_counter = 0; } | |
private: | |
int m_period = 0; | |
int m_counter = 0; | |
}; | |
// just a mock processor, we don't want to inherit juce AudioProcessor here | |
// and needlessly fill in all the needed virtual methods... | |
class MyProcessor | |
{ | |
public: | |
MyProcessor() { m_satimer.setIntervalSamples(11337); } | |
void processBlock(juce::AudioBuffer<float> &buffer, juce::MidiBuffer &midiBuffer) | |
{ | |
m_satimer.Callback = [&midiBuffer](int samplepos) { | |
midiBuffer.addEvent(juce::MidiMessage::noteOn(1, 60, 1.0f), samplepos); | |
// std::cout << "added midi event at buffer position " << samplepos << "\n"; | |
}; | |
m_satimer.advance(buffer.getNumSamples()); | |
} | |
private: | |
SampleAccurateTimer m_satimer; | |
}; | |
void test_sa_timer() | |
{ | |
MyProcessor proc; | |
// simulate what the host is conceptually doing | |
int blocksize = 441; | |
int outcounter = 0; | |
int outlen = 2.5 * 44100; // run simulation for 2.5 seconds | |
juce::AudioBuffer<float> buf(1, blocksize); | |
juce::MidiBuffer midibuffer; | |
while (outcounter < outlen) | |
{ | |
proc.processBlock(buf, midibuffer); | |
midibuffer.clear(); | |
outcounter += blocksize; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment