Cue MidiMessages into audiobuffer from process block

Hi all,
I’m extremely new to C++ and JUCE so please bare with me.

I am trying to create a drum machine plugin, where I can cue drum sounds at certain samples (ex: play kick at sample number 88200). I’m trying to do this by adding custom MidiMessage note on events into a MidiBuffer and passing it into a sampler, as such:

void SamplerAudioProcessor::processBlock (AudioBuffer& buffer, MidiBuffer& midiMessages)
{
ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();

for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
    buffer.clear (i, 0, buffer.getNumSamples())

midiMessages.addEvents(manualMidiBuffer, 0 , 352800, 0);
mSampler.renderNextBlock(buffer, midiMessages, 0, buffer.getNumSamples());

}

where manualMidiBuffer has some MidiMessage note on events. It is clearly not working as I intend it to. Where am I going wrong?

Thanks

The MIDI messages need to be time stamped within the duration of the currently processed audio buffer. (Which are usually pretty short, something like 128-512 samples.) You will need to implement some custom time counting logic which adds the MIDI messages in the correct processBlock call if you want the messages delayed/sequenced. You should probably also handle sending MIDI note off messages even if you are dealing with drum sounds as the voice handling in the destination synthesizer might not work correctly if you don’t send the note offs.

I did some crude illustrations. In the images the vertical black lines show where the processBlock calls happen. They might happen more or less frequently and even “randomly”. In each case the timestamps for the MIDI messages sent into the synthesiser must be different for each processBlock call, while the playback time positions for the notes don’t change.

Thanks! I’ve figured out how to play a sound periodically now, but it doesn’t seem to come up in the DAW… (I’m using Logic for testing). When I manually press a key while recording using my plugin, my sound records, but when I code in a sound using midiMessages.addEvent it only plays the sound on my speakers but it doesn’t record