Using arpeggiator with samples

I’m trying to loop my samples in my standalone plugin from a midi keyboard, using an arpeggiator that repeats using the sample size timing. It’s working, but somehow with an interesting effect that my first loop is cut “randomly” and then after that the sample loops ok. From the arpeggiator example, I got the basic code below (that I will clear some stuff later) :
for (MidiBuffer::Iterator i (midiBuffer); i.getNextEvent (m, time); )
if (m.isNoteOn()) notes.add (m.getNoteNumber());
else if (m.isNoteOff()) notes.removeValue (m.getNoteNumber());
if ((tempo + numSamples) >= noteDuration)
auto offset = jmax (0, jmin ((int) (noteDuration - tempo), numSamples - 1));
if (lastNoteValue > 0){
midiBuffer.addEvent (MidiMessage::noteOff (1, lastNoteValue), offset);
lastNoteValue = -1;

        if (notes.size() > 0)
            currentNote = (currentNote + 1) % notes.size();
            lastNoteValue = notes[currentNote];
            midiBuffer.addEvent (MidiMessage::noteOn  (1, lastNoteValue, (uint8) 127), offset);
     tempo = (tempo + numSamples) % noteDuration;
Note duration will be the sample size (adjusted by num channels, etc). If I clear the midiBuffer, obviously it will play the first loop delayed, and if don't, it will cut somewhere only in the first loop. Any ideas or suggestions about this?

Ups! Easy fix: just init tempo = 0 on “isNoteOn” message. Anyway this works for looping samples. Just need to fix in a way more elegant way…:slight_smile: