Sync to host and LFO?

I built a simple gain plug-in and managed to modulate the gain value in sync with the host. For example every beat change the gain to a random value. I used currentPositionInfo and did some math. Everything is fine but it works only when the host is playing. I would like to have it always changing value (in sync) and when I hit play on my DAW should resets/sync to it. What's the best way of doing it?

I was thinking perhaps to code some kind of LFO with a square wave and sync it with the host tempo, then resetting the phase everytime I hit play. Problem is, I don't know how to do it :) I know the theory of LFO and waves but I'm not sure how can I code it and making it always running. Any suggestions?


The PrepareToPlay() method gets called before each playback. That's where you should put your reinitialisation code.

The PrepareToPlay() method gets called before each playback

This isn't strictly true, this gets called at the mercy of the host but usually only when the block size or sample rate changes. You should also remember that the tempo can change over time in a host so you will have to continually update your LFO rate.

One wat to do it is have your current rate and then work out your target rate when the BPM changes. Then you can modify your current rate by some small amount until it reaches the target. This is needed to avoid clicks when chaging gains or resetting LFOs etc.


I managed to code a pseudo LFO that fill a buffer with +1 and -1 (square wave) and then I check every time in processBlock wheter is +1 or -1 and execute code accordingly. I'm not sure it's the best way of handling it and also I'm still not sure how to reset phase on host play.

Are there any examples of LFO around?

I use to make a free running LFO that runs with the calculated target rate. At the beginning of each process block i calculate the "real" rate and phase that fits the sequencer using ppqPosition and the SigNumerator / Denumerator. This fixes drift errors, synces to the bars and it also works when the host tempo changes. 

Thanks for the reply. My problem is that I don't know how to make a free running LFO. Should I use tables, audio buffers or what? 

For now I just need a square wave, so if I fill a table with 1 and -1, how can I make it "running"? I think I will not have problem syncing the phase once I manage to get something running. Can you help?


Ok I managed to do the free running LFO with tables, it kinda work. Now I have to see how can I reset the phase properly.

Only problem is I have to run the check to the LFO on every sample. Is it safe?

Just run the lfo ind increment the phase with each sample and fix the phase once per processing buffer.