Maestro - Midi Player Tool Kit for Unity Version 2.19.0
Loading...
Searching...
No Matches

Read MIDI events from a MIDI keyboard connected to your Windows or Mac desktop. This class must be used with the prefab MidiInReader.
There is no need to writing a script. For a simple usage, all the job can be done in the prefab inspector. More information here https://paxstellar.fr/prefab-midiinreader/
. More...

Inheritance diagram for MidiPlayerTK.MidiInReader:
MidiPlayerTK.MidiSynth

Public Attributes

EventMidiClass OnEventInputMidi
 Define unity event to trigger when note available from the Midi file.
bool MPTK_ReadMidiInput
 Read Midi input.
ModeSpatializer MPTK_ModeSpatializer
 Current routing mode for MidiSpatializer (MIDI Spatial Mapper).
int MPTK_MaxSpatialSynth
 Gets or sets the maximum number of spatial synth instances that can be created/used by MidiSpatializer.
bool MPTK_SpatialSynthEnabled
 In MidiSpatializer mode, not all MidiSynth instances are active.
True if this synth instance is currently enabled for spatial rendering.
int MPTK_InstrumentNum
 In Track mode, contains the program number (preset) of the last instrument played.
MPTKSoundFont MPTK_SoundFont = null
 At runtime, SoundFonts can be loaded dynamically from the local file system or directly from the web. This avoids embedding a SoundFont in your build, which is ideal for in-app purchases or downloadable content. Legacy mode still allows loading SoundFonts from the internal MPTK database. Maestro MPTK also lets you assign different SoundFonts to different MIDI players (MidiFilePlayer, MidiStreamPlayer, ...), enabling flexible, per-player audio rendering.
float MPTK_LeanSynthStarting = 0.05f
 Gets or sets the initial volume level of the synthesizer at application startup. This property allows for a gradual increase in volume to prevent abrupt or unusual sounds when the application begins.
bool MPTK_EnablePresetDrum
 Accept preset changes on Drum Channel 9 (percussion). Enabling this can produce unexpected results with MIDI files that are not standard-compliant. If disabled, preset changes on channel 9 are ignored (preset 0 remains in use).
bool MPTK_ReleaseSameNote = true
 If the same note is hit twice on the same channel, the older voice is advanced to the release stage. This is the default MIDI processing behavior.
bool MPTK_KillByExclusiveClass = true
 Finds the exclusive class of this voice. When enabled, stops all voices that share the exclusive class and were created after the first voice for this note-on event.
float MPTK_ReleaseTimeMod = 1f
 When a note is stopped with a note-off or when its duration is over, it continues to play for a short time depending on the instrument. This parameter multiplies the default release time defined in the SoundFont for each instrument. Recommended values are between 0.1 and 10. Default is 1 (no change to the release time). Performance note: the longer the release, the more CPU is used after note-on, because many samples may play simultaneously.
float MPTK_CutOffVolume = 0.0001f
 When the amplitude of a sample falls below this value, playback stops. Increasing the value can improve performance when many samples play concurrently, but may stop samples too early and reduce quality. Remember: amplitude ranges between 0 and 1.
bool MPTK_ApplyRealTimeModulator
 Gradually ramps the synth volume at startup to avoid artifacts. Controls how quickly the audio source reaches full volume. Set to 1 for an immediate full level at start.
bool MPTK_ApplyModLfo
 Apply LFO effect defined in the SoundFont.
bool MPTK_ApplyVibLfo
 Apply vibrato effect defined in the SoundFont.
bool MPTK_DirectSendToPlayer
 If true (default) then MIDI events are sent automatically to the MIDI player. Sets to false if you want to process events without playing sound. OnEventNotesMidi Unity Event can be used to process each note.
bool MPTK_EnableChangeTempo
 Enable tempo changes from the MIDI file during playback. If disabled, only the first tempo change in the MIDI file is applied (or 120 BPM if none is found). Disable this when you want to control tempo from your script.
bool MPTK_EnablePanChange
 Apply pan changes from MIDI events in the SoundFont. Pan is disabled when spatialization is activated.
bool MPTK_WeakDevice
 Optimize playback for low-power devices (for example, budget smartphones). Applies only in AudioSource mode (MPTK_CorePlayer = false). Enabling this may cause imperfect MIDI interpretation and lower sound quality.
uint MPTK_ReleaseTimeMin = 500000
 [Only when CorePlayer = false] Defines a minimum release time at note-off in 100-nanosecond units. The 50 ms default is a good tradeoff; shorter values can produce unpleasant artifacts. No effect when MPTK_CorePlayer is true.
int MPTK_ThreadMidiWait = 10
 Delay (in milliseconds) that the MIDI sequencing thread waits between processing MIDI event batches.
bool MPTK_AutoBuffer = true
 Enable voice buffering to improve runtime performance.
int MPTK_AutoCleanVoiceLimit
 Removes free voices older than MPTK_AutoCleanVoiceTime once their count exceeds MPTK_AutoCleanVoiceLimit.
float MPTK_AutoCleanVoiceTime
 Delay (in milliseconds) that the MIDI sequencing thread waits between processing MIDI event batches.
MPTKEffectSoundFont MPTK_EffectSoundFont
 A SoundFont defines parameters for three kinds of effects: low-pass filter, reverb, and chorus. These parameters can be specific to each instrument and even each voice. Maestro MPTK effects are based on FluidSynth algorithmic effect modules. Maestro Pro can increase or decrease the impact of these effects (from the inspector or by script). To summarize:
MPTKEffectUnity MPTK_EffectUnity
 Unlike SoundFont effects, Unity audio effects apply to the whole player. Their parameters are richer and rely on Unity's audio algorithms.
https://docs.unity3d.com/Manual/class-AudioEffectMixer.html
Maestro integrates the most important effects: Reverb and Chorus. Other effects could be added if needed.
bool MPTK_AudioSettingFromUnity
 Use the audio settings provided by Unity instead of custom values.
bool MPTK_EnableFreeSynthRate = false
 Allow direct setting of the Synth Rate.
bool MPTK_LogEvents
 Log MIDI events (v2.9.0 moved from MidiFilePlayer).
bool MPTK_LogWave
 Log for each sample to be played.
int MPTK_StatVoiceCountPlaying
 Count of active voices (playing, excluding voices in release). Sound may still be audible from voices in release even when this count is 0. Read-only.
int MPTK_StatVoiceCountActive
 Count of the active voices (playing and releasing) - Readonly.
int MPTK_StatVoiceCountReused
 Count of the voices reused - Readonly.
int MPTK_StatVoiceCountFree
 Count of free voices available for reuse. Voices older than AutoCleanVoiceTime are removed only when the count exceeds AutoCleanVoiceLimit. Read-only.
int MPTK_StatVoiceRatioReused
 Percentage of voices reused during the synth lifetime. 0: no reuse, 100: all voices reused (unattainable in practice).
int MPTK_StatVoicePlayed
 Count of voice played since the start of the synth.
EventSynthClass OnEventSynthAwake
 Unity event fired during the synthesizer's Awake. The GameObject component name is passed as a parameter. Setting this callback via script (AddListener) is not recommended; prefer setting it from the inspector.
EventSynthClass OnEventSynthStarted
 Unity event fired when the synthesizer starts. The GameObject component name is passed as a parameter. Setting this callback via script (AddListener) is not recommended; prefer setting it from the inspector.
Func< MPTKEvent, bool > OnMidiEvent
 Called by the MIDI sequencer before sending a MIDI message to the synthesizer.
From version 2.10.0 onward, the callback must return true to keep the event or false to skip it.
Action< int, long, int, int > OnBeatEvent
 Invoked on each beat with the following parameters:
float MPTK_OrientationToListener
 Returns the signed angle (in degrees) between the sound source and the AudioListener.
bool MPTK_PauseOnMaxDistance = true
 If true, the MIDI player will be automatically paused when the distance from the listener exceeds MPTK_MaxDistance.

Properties

MPTKChannels MPTK_Channels [get]
 Description and list of MIDI Channels associated to the MIDI synth.
Each MIDI synth has 16 channels that carry all the relevant MIDI information.
int MPTK_SpatialSynthIndex [get]
 Index of the MidiSynth for the dedicated Channel or Track when the prefab MidiSpatializer is used. If MPTK_ModeSpatializer = Channel then represent the playing channel. If MPTK_ModeSpatializer = Track then represent the playing track. The value is -1 for the Midi reader because no voice is played.
bool MPTK_IsSpatialSynthMaster [get]
 True if this MidiSynth is the master spatial synth used by MidiSpatializer.
The master synth reads MIDI events and dispatches them to the other spatial synth instances.
string MPTK_InstrumentPlayed [get]
 In Track mode, returns the name of the last instrument played on this track.
Empty string if unknown.
string MPTK_TrackName [get]
 In Track mode, returns the last known track name.
Empty string if the MIDI file does not provide SequenceTrackName.
bool MPTK_KeepPlayingNonLooped [get, set]
 When the value is true, NoteOff and Duration for non-looped samples are ignored and the samples play through to the end.
float MPTK_VelocityAttenuation [get, set]
 Experimental feature: modify the Fluidsynth constant FLUID_PEAK_ATTENUATION to change how velocity affects the voice attenuation. The default value is 960 (96 Db) Other values may produce unwanted results, use with care!
float MPTK_Volume [get, set]
 Sets the global volume between 0 and 1 for the current MPTK Synth.
int MPTK_Transpose [get, set]
 Transposes notes from -24 to +24 semitones.
int MPTK_TransExcludedChannel [get, set]
 Transposition applies to all channels except this one. Set to -1 to apply to every channel. V2.89.0 Default is 9 because drums are generally on channel 9.
bool MPTK_Dsp64 [get, set]
 Accept preset changes on Drum Channel 9 (percussion). Enabling this can produce unexpected results with MIDI files that are not standard-compliant. If disabled, preset changes on channel 9 are ignored (preset 0 remains in use).
int MPTK_ThreadMidiPriority [get, set]
 The MIDI thread priority controls how often the thread is scheduled by the CPU. The default value is 0 (normal); you can increase it to 1 or 2 (higher) on weaker hardware for more stable MIDI reading.
bool MPTK_CorePlayer [get, set]
 If true, the synth rate and buffer size are set automatically by Unity according to the hardware capability. - V2.89.0 - See Unity menu "Edit / Project Settings..." to choose between best latency and best performance. If false, you can set rate and buffer size manually, at the risk of degraded audio quality (experimental).
int MPTK_SynthRate [get, set]
 Gets or sets the current synth rate (only if MPTK_EnableFreeSynthRate is true).
int MPTK_IndexSynthRate [get, set]
 Gets or sets the synth output sample rate. -1: default, 0: 24000, 1: 36000, 2: 48000, 3: 60000, 4: 72000, 5: 84000, 6: 96000. It's better to stop playback before changing on the fly to avoid noise.
int MPTK_IndexSynthBuffSize [get, set]
 Gets or sets synth buffer size: -1: default, 0: 64, 1: 128, 2: 256, 3: 512, 4: 1024, 5: 2048. The change is global for all prefabs. Stop playback on all prefabs before changing on the fly to avoid noise or crashes.
int MPTK_StatVoiceCountSustained [get]
 Gets the number of active voices currently in the sustained state.
bool MPTK_Orientation [get, set]
 Enables orientation-based audio behavior (Pro).
bool MPTK_DistanceAttenuation [get, set]
 Enables Unity distance-based attenuation (min/max distance and custom rolloff curve). When enabled, MPTK configures the underlying AudioSource with:
float MPTK_MinDistance [get, set]
 When MPTK_DistanceAttenuation is enabled, the volume of the audio source depends on the distance between the audio source and the listener. Distance at which attenuation begins. When the listener is closer than this value, the audio plays at full volume(1.0).
float MPTK_MaxDistance [get, set]
 When MPTK_DistanceAttenuation is enabled, the volume of the audio source depends on the distance between the audio source and the listener. Distance at which attenuation reaches its minimum level. Beyond this distance, the volume remains constant and does not decrease further.
float MPTK_MinSoundAttenuation [get, set]
 If MPTK_DistanceAttenuation is enabled, the volume of the audio source depends on the distance between the audio source and the listener. Minimum volume applied at Max Distance.

Additional Inherited Members

enum  ModeSpatializer { Channel , Track }
 Routing mode used by the MidiSpatializer prefab (MIDI Spatial Mapper).
Selects how incoming Note On events are dispatched to spatial synth instances. More...
Public Member Functions inherited from MidiPlayerTK.MidiSynth
IEnumerator MPTK_WaitAllNotesOff (int _idSession=-1)
 Waits until all notes are off. This may take a few seconds because samples must complete their release time. The method exits after a 3-second timeout. *** Use this method only as a coroutine. ***.
void MPTK_InitSynth (int channelCount=16, bool preserveChannelInfo=false, bool preserveActivVoice=true)
 Initializes the synthesizer:
void MPTK_InitModulators ()
 Initializes the default MIDI modulators for the synthesizer, mapping standard MIDI inputs to corresponding sound synthesis parameters according to SoundFont 2.01 specifications.
void MPTK_StartSequencerMidi ()
 Starts the MIDI sequencer: each MIDI event is read and played on a dedicated thread. This thread is started automatically by the MidiFilePlayer, MidiListPlayer, and MidiExternalPlayer prefabs.
void MPTK_StartSynth ()
 Starts processing samples by the synth and the MIDI sequencer. Useful only after calling MPTK_StopSynth when using MidiStreamPlayer.
void MPTK_StopSynth ()
 Stops processing samples by the synth and the MIDI sequencer. See also MPTK_StartSynth.
void MPTK_ClearAllSound (bool destroyAudioSource=false, int _idSession=-1)
 Clears all sound by sending NoteOff messages. This can take a few seconds because sample release times must play out.
void MPTK_DebugActiveVoice ()
 Log information about active voices.
void MPTK_DebugFreeVoice ()
 Log information about free voices.
void MPTK_ResetStat ()
 Reset voices statistics.
delegate void OnAudioFrameStartHandler (double synthTime)
 Delegate for the OnAudioFrameStart event.
void MPTK_PlayDirectEvent (MPTKEvent midiEvent, bool playNoteOff=true)
 Plays a single MIDI event immediately. Processing is synchronous: the method returns only after the MIDI event has been handled by the synth.
void MPTK_StopDirectEvent (MPTKEvent midiEvent)
 Stops immediately the MIDI event played with @MPTK_PlayDirectEvent. Processing is synchronous: the method returns after all voices for the notes have been handled by the synth.
void MPTK_PauseVoices (float transitionDuration=30f)
 Pauses all active voices using the specified transition duration.
void MPTK_ResumeVoices (float transitionDuration=30f)
 Resumes all active voices using the specified transition duration.
static List< MidiFilePlayerSpatialSynths
 Contains each Midi Synth for each channel or track when the prefab MidiSpatializer is used and IsMidiChannelSpace=true. Warning: only one MidiSpatializer can be used in a hierarchy.
OnAudioFrameStartHandler OnAudioFrameStart
 Raised at the start of each audio frame by the audio engine.
.

Detailed Description

Read MIDI events from a MIDI keyboard connected to your Windows or Mac desktop. This class must be used with the prefab MidiInReader.
There is no need to writing a script. For a simple usage, all the job can be done in the prefab inspector. More information here https://paxstellar.fr/prefab-midiinreader/
.

Attention
MidiInReader inherits of class MidiSynth. For clarity, only MidiInReader attibutes are provided here. Look at the class MidiSynth to discover all attributes available.
Version
Maestro Pro

Example of script. See TestMidiInputScripting.cs for a more detailed usage.
Display each MIDI events from a MIDI device connected Need for a reference to the Prefab (can also be set from the hierarchy)

MidiInReader midiIn = FindFirstObjectByType<MidiInReader>();
if (midiIn == null)
Debug.LogWarning("Can't find a MidiInReader Prefab in the current Scene Hierarchy. Add it with the MPTK menu.");
// There is two methods to trigger event: in inpector from the Unity editor or by script
midiIn.OnEventInputMidi.AddListener((MPTKEvent evt) =>
{
// your processing here
Debug.Log(evt.ToString());
});
Represents a MIDI event used throughout MPTK. This class is central to script-based MIDI workflows in...
Definition MPTKEvent.cs:59
override string ToString()
Builds a string description of this MIDI event. Since v2.83, returned strings no longer contain trail...
Definition MPTKEvent.cs:546
Read MIDI events from a MIDI keyboard connected to your Windows or Mac desktop. This class must be us...
Definition MidiInReader.cs:36
EventMidiClass OnEventInputMidi
Define unity event to trigger when note available from the Midi file.
Definition MidiInReader.cs:59

Member Data Documentation

◆ OnEventInputMidi

EventMidiClass MidiPlayerTK.MidiInReader.OnEventInputMidi

Define unity event to trigger when note available from the Midi file.

MidiInReader midiFilePlayer = FindFirstObjectByType<MidiInReader>();
...
if (!midiFilePlayer.OnEventInputMidi.HasEvent())
{
// No listener defined, set now by script. NotesToPlay will be called for each new notes read from Midi file
midiFilePlayer.OnEventInputMidi.AddListener(NotesToPlay);
}
...
public void NotesToPlay(MPTKEvent notes)
{
Debug.Log(notes.Value);
foreach (MPTKEvent midievent in notes)
{
...
}
}
int Value
Numeric message data whose meaning depends on Command.
Definition MPTKEvent.cs:130

Property Documentation

◆ MPTK_Channels

MPTKChannels MidiPlayerTK.MidiInReader.MPTK_Channels
get

Description and list of MIDI Channels associated to the MIDI synth.
Each MIDI synth has 16 channels that carry all the relevant MIDI information.

  • Current instrument / bank
  • Volume
  • Mute / Unmute (see Enable)
  • Pitch bend ...

They serve to distinguish between instruments and provide independent control over each one.
By transmitting MIDI messages on their respective channels, you can alter the instrument, volume, pitch, and other parameters.
Within the Maestro Midi Player Toolkit, MIDI channels are designated numerically from 0 to 15. Notably, channel 9 is set aside specifically for drum sounds.

HelperDemo.GUI_Horizontal(HelperDemo.Zone.BEGIN);
GUILayout.Label("Channel Preset Name Preset / Bank",
myStyle.TitleLabel3, GUILayout.Width(60 + 140 + 120 + 100 + 110));
GUILayout.Label(" Count Enabled Volume",
myStyle.TitleLabel3, GUILayout.Width(900));
HelperDemo.GUI_Horizontal(HelperDemo.Zone.END);
// Also available for MidiStreamPlayer, MidiInReader, MidiExternalPlayer.
for (int channel = 0; channel < midiFilePlayer.MPTK_Channels.Length; channel++)
{
HelperDemo.GUI_Horizontal(HelperDemo.Zone.BEGIN);
// Display channel number and log info
if (GUILayout.Button($" {channel:00}", myStyle.TitleLabel3, GUILayout.Width(60)))
Debug.Log(midiFilePlayer.MPTK_Channels[channel].ToString());
// Display preset name
GUILayout.Label(midiFilePlayer.MPTK_Channels[channel].PresetName ?? "not set", myStyle.TitleLabel3, GUILayout.Width(140));
// Display preset and bank index
int presetNum = midiFilePlayer.MPTK_Channels[channel].PresetNum;
int bankNum = midiFilePlayer.MPTK_Channels[channel].BankNum;
int presetForced = midiFilePlayer.MPTK_Channels[channel].ForcedPreset;
// Check if preset is forced and build a string info
string sPreset = presetForced == -1 ? $"{presetNum} / {bankNum}" : $"F{presetForced} / {bankNum}";
// Slider to change the preset on this channel from -1 (disable forced) to 127.
int forcePreset = (int)HelperDemo.GUI_Slider(sPreset, presetNum, -1f, 127f, alignCaptionRight: true, widthCaption: 120, widthSlider: 100, widthLabelValue: -1);
if (forcePreset != presetNum)
{
// Force a preset and a bank whatever the MIDI events from the MIDI file.
// set forcePreset to -1 to restore to the last preset and bank value known from the MIDI file.
// let forcebank to -1 to not force the bank.
// Before v2.10.1 midiFilePlayer.MPTK_ChannelForcedPresetSet(channel, forcePreset, forceBank);
midiFilePlayer.MPTK_Channels[channel].ForcedBank = forceBank;
midiFilePlayer.MPTK_Channels[channel].ForcedPreset = forcePreset;
}
// Display count note by channel
GUILayout.Label($"{midiFilePlayer.MPTK_Channels[channel].NoteCount,-5}", myStyle.LabelRight, GUILayout.Width(100));
// Toggle to enable or disable a channel
GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(20));
bool state = GUILayout.Toggle(midiFilePlayer.MPTK_Channels[channel].Enable, "", GUILayout.MaxWidth(20));
if (state != midiFilePlayer.MPTK_Channels[channel].Enable)
{
midiFilePlayer.MPTK_Channels[channel].Enable = state;
Debug.LogFormat("Channel {0} state:{1}, preset:{2}", channel, state, midiFilePlayer.MPTK_Channels[channel].PresetName ?? "not set"); /*2.84*/
}
// Slider to change volume
float currentVolume = midiFilePlayer.MPTK_Channels[channel].Volume;
float volume = HelperDemo.GUI_Slider(null, currentVolume, 0f, 1f, alignCaptionRight: true, enableButton: false, widthCaption: -1, widthSlider: 100, widthLabelValue: 40);
if (volume != currentVolume)
midiFilePlayer.MPTK_Channels[channel].Volume = volume;
HelperDemo.GUI_Horizontal(HelperDemo.Zone.END);
}