Audio problem with VST HOST

I created a simple VST host to send midi file to Kontakt.
It works fine but if the midi is more than 48 seconds the music stops in the middle and I hear a long last note. I tested it with several midis. Always happens after 48 seconds. I guess there is some kind of problem the way I use MidiBuffer and AudioSampleBuffer, but I can’t find the reason.
My code:

void RenderKontakt::loadMidi (const String& filename, const String& wavfile)

FileInputStream fileStream(filename);
MidiFile Mfile;
MidiBuffer midiBuffer;
float totalTime = 0;
float TrackTotalTime = 0;
for (int t = 0; t < Mfile.getNumTracks(); t++) {
    const MidiMessageSequence* track = Mfile.getTrack(t);
    TrackTotalTime = track->getEndTime();
    if (totalTime < TrackTotalTime)
        totalTime = TrackTotalTime;
    for (int i = 0; i < track->getNumEvents(); i++) {
        MidiMessage& m = track->getEventPointer(i)->message;
        std::cout<<m.getDescription ()<<" time:" << m.getTimeStamp() << "\n";
        int sampleOffset = (int)(sampleRate * m.getTimeStamp());
        midiBuffer.addEvent(m, sampleOffset);
        TrackTotalTime = m.getTimeStamp();
int numberOfBuffers = int (std::ceil ((totalTime) * sampleRate / bufferSize));
// Data structure to hold multi-channel audio data.
AudioSampleBuffer audioBuffer (plugin->getTotalNumOutputChannels(),
plugin->prepareToPlay (sampleRate, bufferSize);
File outputFile = File(wavfile);
WavAudioFormat format;
std::unique_ptr<AudioFormatWriter> writer;
writer.reset (format.createWriterFor (new FileOutputStream (outputFile),

plugin->setNonRealtime (true);
for (int i = 0; i < numberOfBuffers; ++i)
    plugin->processBlock (audioBuffer, midiBuffer);
    if (writer != nullptr)
        writer->writeFromAudioSampleBuffer (audioBuffer, 0, audioBuffer.getNumSamples());


Maybe Kontakt (or Juce) doesn’t like that you put the same MIDI messages into the plugin at each buffer render cycle. As far as I’ve understood, only the MIDI messages that are relevant for the particular buffer should be given to the plugins.

I use midi files that include several tracks and messages that should be play simultaneously. Thus it is necessary to send to the plugin the whole midi messages or to find a way to divide it in such a way the translation to audio will still be correct. I think it should be an easy way to do that, but I wonder how…I tried to artificially divide the midi file, but it seems to be very complicated. Any thoughts?

Have you tested some other, simpler, instrument plugin?

No. I worked only with Kontakt. I make manipulation and AI for midi files and then I want to use a good sampler. Till now I used midi files less than 48 seconds so it worked fine…

Hey, did you solve that problem? I tried to run this code, but found there is basically no sound, though the duration of the WAV file is correct.