MusIT

Prefab MidiFileLoader

The prefab MidiFileLoader is useful for loading all or a part of the MIDI events from a Midi file.

There is no MIDI Sequencer, no MIDI Synthesizer, no music playing capabilities, just loading and decoding a MIDI file to a list of MPTKEvent. Obviously, this prefab has some interest only for scripting.

MIDI can be loaded from the MidiDB list (see Unity menu MPTK / Midi Player Setup) or from a folder on the desktop (Pro).

Classically, the Prefab can be added to the scene hierachy:

C#
// A MidiFileLoader prefab must be added to the hierarchy with the editor (see menu MPTK)
MidiFileLoader midiFileLoader = FindObjectOfType<MidiFileLoader>();

Or it can be created and loaded only by script:

C#
MidiFileLoader midiFileLoader;

private void Awake()
{
    // MidiPlayerGlobal is a singleton: only one instance can be created. 
    if (MidiPlayerGlobal.Instance == null)
    gameObject.AddComponent<MidiPlayerGlobal>();
            
    // When running, this component will be added to this gameObject
    midiFileLoader = gameObject.AddComponent<MidiFileLoader>();
}

Then reading the MIDI contents is easy:

C#
// Select a MIDI from the MIDI DB (with exact name)
midiFileLoader.MPTK_MidiName = "Bach - Fugue";
// Load the MIDI file
if (midiFileLoader.MPTK_Load())
{
   // Read all MIDI events
   List<MPTKEvent> sequence = midiFileLoader.MPTK_ReadMidiEvents();
   Debug.Log($"Loading '{midiFileLoader.MPTK_MidiName}', MIDI events count:{sequence.Count}");
}
else
   Debug.Log($"Loading '{midiFileLoader.MPTK_MidiName}' - Error");