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

Core sample-based SoundFont synthesizer (base class). More...

Inheritance diagram for MidiPlayerTK.MidiSynth:
MidiPlayerTK.MidiFilePlayer MidiPlayerTK.MidiFilePlayer MidiPlayerTK.MidiInReader MidiPlayerTK.MidiStreamPlayer MidiPlayerTK.MidiStreamPlayer MidiPlayerTK.MidiExternalPlayer MidiPlayerTK.MidiSpatializer MidiPlayerTK.MidiExternalPlayer MidiPlayerTK.MidiSpatializer

Public Member Functions

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. ***.

MIDI Spatial Mapper

Spatial routing system used by the MidiSpatializer prefab.

The MIDI Spatial Mapper distributes incoming MIDI events from the main MIDI reader to multiple MidiSynth instances in the scene. This allows instruments or tracks to be rendered from different spatial positions.

Two routing modes are available:

  • Channel mode: one spatial synth per MIDI channel.
  • Track mode: one spatial synth per MIDI track.

This system is typically used with the MidiSpatializer prefab to create immersive 3D audio scenes.

Version
Maestro Pro
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...
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.
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.
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.

SoundFont Management

Runtime loading, caching, and access to SoundFont banks and presets.

This section provides the API used to manage SoundFonts in Maestro MPTK.

A SoundFont defines the instruments, banks, presets, and samples used by the synthesizer to render MIDI events. MPTK allows SoundFonts to be loaded and switched dynamically while the application is running.

SoundFonts can be loaded from:

When loading from external sources, SoundFonts can optionally be downloaded, cached locally, or reused from the cache to reduce loading time.

This API also provides access to the structure of the loaded SoundFont, including the list of available banks and presets for instruments and drums. These lists can be used to build user interfaces or to select banks before applying MIDI preset changes.

Additionally, callbacks are available to monitor download progress and to be notified when a SoundFont has finished loading.

Note
Changing banks or presets through this API updates the available preset lists but does not directly change the currently active instrument in the synthesizer. To change instruments during playback, use the MIDI channel API (see MidiStreamPlayer.MPTK_Channels for the MIDI Stream prefab).
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.

Synthesizer Initialization And Life Cycle

Initialization and lifecycle of the MIDI synthesizer.

This section contains methods and parameters related to the creation and initialization of the MIDI synthesizer. These functions configure the audio engine, load SoundFonts, and prepare the synth for playback.

In most cases initialization is handled automatically by the prefab, but advanced users may control it directly from scripts.

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.
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.

Synthesizer Settings

Settings of the MIDI synthesizer.

This section contains methods and parameters related the audio engine configuration.

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.
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).

Synthesizer Performance

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.
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.

Audio Effects

Integration of Unity audio effects applied to the synthesizer.

Unlike SoundFont effects which operate at the instrument level, Unity audio effects are applied to the entire output of the MIDI synthesizer.

Maestro integrates selected Unity effects such as Reverb and Chorus. These effects can be configured from the inspector or controlled directly from scripts at runtime.

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.

Audio Settings

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_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.

Log & Debug

bool MPTK_LogEvents
 Log MIDI events (v2.9.0 moved from MidiFilePlayer).
bool MPTK_LogWave
 Log for each sample to be played.
void MPTK_DebugActiveVoice ()
 Log information about active voices.
void MPTK_DebugFreeVoice ()
 Log information about free voices.

Voice Statistics

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.
int MPTK_StatVoiceCountSustained [get]
 Gets the number of active voices currently in the sustained state.
void MPTK_ResetStat ()
 Reset voices statistics.

Synthesizer Events

Events raised by the MIDI synthesizer during playback.

These callbacks allow scripts to interact with the synthesizer during audio processing. Some events may run on the audio processing thread, therefore Unity API calls are generally not allowed except Debug.Log.

Typical uses include:

  • monitoring playback timing
  • intercepting MIDI events
  • synchronizing gameplay with music.
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:
OnAudioFrameStartHandler OnAudioFrameStart
 Raised at the start of each audio frame by the audio engine.
.
delegate void OnAudioFrameStartHandler (double synthTime)
 Delegate for the OnAudioFrameStart event.

3D Orientation and Attenuation

Real-time spatial audio processing based on listener orientation.

These parameters control how the synthesizer audio reacts to the position and orientation of the AudioListener.

Features include:

  • stereo panning based on listener direction
  • front/back filtering
  • distance attenuation

The goal is to simulate directional sound perception and improve spatial immersion when MIDI instruments are placed in a 3D scene.

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.
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.

MIDI Direct Play

Send a single MIDI event directly to the synthesizer (immediate, synchronous).

This section provides low-level methods to play or stop one MIDI event without using the MIDI sequencer. The event is processed immediately by the synth and the method returns only after the event has been handled.

Supported commands include:

  • NoteOn (Velocity 0 is treated as NoteOff)
  • NoteOff (optional handling via playNoteOff)
  • ControlChange (applied only when MPTK_ApplyRealTimeModulator is enabled)
  • PatchChange (with drum channel rules depending on MPTK_EnablePresetDrum)
  • PitchWheelChange
  • MetaEvent (TextEvent may trigger action parsing in Pro builds)

Typical use cases:

  • trigger one-shot notes or SFX
  • real-time modulation (CC, pitch bend)
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.

Pause and Resume Voices

Runtime control of active synthesizer voices.

This section provides methods to pause or resume all currently active voices with smooth transitions. The transition duration controls how quickly voices fade out or fade back in.

These functions are useful for:

  • implementing transport controls
  • temporarily muting playback
  • synchronizing audio with gameplay or UI events.
    Version
    Maestro Pro
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.

Detailed Description

Core sample-based SoundFont synthesizer (base class).

Maestro MPTK Pro extension for MidiSynth.

Base class which contains all the stuff to build a Wave Table Synth.

Loads a SoundFont and its samples, processes incoming MIDI events, and renders voices (controllers, generators, etc.). The synthesis engine is a C# adaptation of FluidSynth tailored for Unity audio integration. This class is the common base used by the MPTK prefabs: MidiStreamPlayer, MidiFilePlayer, and MidiInReader.

Do not instantiate MidiSynth directly. Instead, add one of the MPTK prefabs to your scene and access its properties and methods from your scripts.

Examples:

midiFilePlayer.MPTK_ChorusDelay = 0.2f;
midiStreamPlayer.MPTK_InitSynth();

Loads SoundFont and samples, process midi event, play voices, controllers, generators ...
This class is inherited by others class to build these prefabs: MidiStreamPlayer, MidiFilePlayer, MidiInReader.
It is not recommended to instanciate directly this class, rather add prefabs to the hierarchy of your scene. and use attributes and methods from an instance of them in your script. Example:

  • midiFilePlayer.MPTK_ChorusDelay = 0.2
  • midiStreamPlayer.MPTK_InitSynth()
Version
Maestro Pro

Member Enumeration Documentation

◆ ModeSpatializer

Routing mode used by the MidiSpatializer prefab (MIDI Spatial Mapper).
Selects how incoming Note On events are dispatched to spatial synth instances.

Version
Maestro Pro
Enumerator
Channel 

Dispatch Note On events by MIDI channel.
Reminder: a MIDI channel plays one instrument at a time.
Instruments (presets) are selected per channel with MPTKCommand.PatchChange.

Track 

Dispatch Note On events by MIDI track.
Reminder: a track may contain multiple MIDI channels, therefore multiple instruments.
Track names come from the Meta MIDI event SequenceTrackName.
This meta event is not always present in MIDI files, so the track name may be empty.

Member Function Documentation

◆ MPTK_WaitAllNotesOff()

IEnumerator MidiPlayerTK.MidiSynth.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. ***.

// Call this method with: StartCoroutine(NextPreviousWithWait(false));
// See TestMidiFilePlayerScripting.cs
public IEnumerator NextPreviousWithWait(bool next)
{
midiFilePlayer.MPTK_Stop();
yield return midiFilePlayer.MPTK_WaitAllNotesOff(midiFilePlayer.IdSession);
if (next)
midiFilePlayer.MPTK_Next();
else
midiFilePlayer.MPTK_Previous();
CurrentIndexPlaying = midiFilePlayer.MPTK_MidiIndex;
yield return 0;
}
Parameters
_idSessionClear only samples playing in this session; -1 clears all.
Returns

◆ MPTK_PlayDirectEvent()

void MidiPlayerTK.MidiSynth.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.

Warning
This method should be used sparingly, method returns only after the event has been fully handled. For sending a large number of MIDI events, it is recommended to use the MidiStreamPlayer prefab with #MPTK_PlayEvent. In this case events are queued and processed efficiently by the internal MIDI event stack.
// OnBeatEvent (pro) is triggered by the MPTK MIDI sequencer at each beat independently of MIDI events
// - OnBeatEvent is executed at each beat even if there is there no MIDI event on the beat.
// - Accuracy is guaranteed (internal thread).
// - Direct call to Unity API is not possible (but you have access to all your script variables and most part of the MPTK API).
// Parameters received:
// - time Time in milliseconds since the start of the playing MIDI.
// - tick Current tick of the beat.
// - measure Current measure (start from 1).
// - beat Current beat (start from 1).
midiFilePlayer.OnBeatEvent = (int time, long tick, int measure, int beat) =>
{
if (FoldOutMetronome)
{
// Calculate the value to be displayed on the FoldOut Metronome and on the log
beatTimeTick = $"Time: {TimeSpan.FromMilliseconds(time)} Tick: {tick}";
beatMeasure = $"Beat/Measure: {beat}/{measure}";
Debug.Log($"OnBeatEvent - {beatTimeTick} Signature segment:{midiFilePlayer.MPTK_MidiLoaded.MPTK_CurrentSignMap.Index} {beatMeasure}");
// for testing interaction with Maestro MPTK player
if (stopPlayingAtMeasure != -1 && measure >= stopPlayingAtMeasure)
// Stops playback of the MIDI file. But the triggering event could be still playing (too late for stop it).
midiFilePlayer.MPTK_Stop(false);
// Plays an extra drum sound with each beat
midiFilePlayer.MPTK_PlayDirectEvent(new MPTKEvent()
{
Command = MPTKCommand.NoteOn,
Channel = 9,
Value = instrumentMetronome,
Velocity = volumeMetronome,
Measure = measure,
Beat = beat
});
}
};
Parameters
midiEvent

◆ MPTK_StopDirectEvent()

void MidiPlayerTK.MidiSynth.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.

Parameters
midiEvent

◆ OnAudioFrameStartHandler()

delegate void MidiPlayerTK.MidiSynth.OnAudioFrameStartHandler ( double synthTime)

Delegate for the OnAudioFrameStart event.

Version
Maestro Pro

◆ MPTK_PauseVoices()

void MidiPlayerTK.MidiSynth.MPTK_PauseVoices ( float transitionDuration = 30f)

Pauses all active voices using the specified transition duration.

Note
  • Iterates over all active voices and pauses them with the given transition duration.
See also
MPTK_ResumeVoices Example with the MidiStreamPlayer prefab:
midiStreamPlayer.MPTK_PauseVoices(100);
Version
2.17.0 Pro

◆ MPTK_ResumeVoices()

void MidiPlayerTK.MidiSynth.MPTK_ResumeVoices ( float transitionDuration = 30f)

Resumes all active voices using the specified transition duration.

Note
  • Iterates over all active voices and resumes them with the given transition duration.
See also
MPTK_PauseVoices Example with the MidiStreamPlayer prefab:
midiStreamPlayer.MPTK_ResumeVoices(100);
Version
2.17.0 Pro

Member Data Documentation

◆ MPTK_SoundFont

MPTKSoundFont MidiPlayerTK.MidiSynth.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.

Version
2.15 An instance of this class is automatically created when the MPTK prefab is loaded in the scene. See MPTKSoundFont class for more details.
Note

◆ MPTK_EnablePresetDrum

bool MidiPlayerTK.MidiSynth.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).

Note
  • Bank 128 and preset 0 are generally used for drum kits.
Attention

◆ MPTK_CutOffVolume

float MidiPlayerTK.MidiSynth.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.

Version
2.9.1 // was 0.03

◆ MPTK_ApplyRealTimeModulator

bool MidiPlayerTK.MidiSynth.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.

Apply real-time modulator effects defined in the SoundFont: pitch bend, control change, envelope modulation.

◆ MPTK_AutoBuffer

bool MidiPlayerTK.MidiSynth.MPTK_AutoBuffer = true

Enable voice buffering to improve runtime performance.

When enabled:

When disabled, voices whose state becomes OFF are removed directly from the Active list.

◆ MPTK_EffectSoundFont

MPTKEffectSoundFont MidiPlayerTK.MidiSynth.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:

  • Effects are applied per voice but are statically defined in the SoundFont.
  • Maestro parameters can raise or lower the default values set in the SoundFont.
  • Adjustments apply to the whole prefab; the audible result depends on the initial SoundFont preset.
  • These effects require additional CPU resources. See more detailed information at https://paxstellar.fr/sound-effects/
    Note
  • By default, only the low-pass filter effect is enabled in Maestro.
  • Enable other effects from the prefab inspector (Synth Parameters / SoundFont Effect) or by script.
  • The low-pass filter often improves sound quality and is enabled by default.
    // Find a MPTK Prefab, will work also for MidiStreamPlayer, MidiExternalPlayer ... all classes which inherit from MidiSynth.
    MidiFilePlayer fp = FindFirstObjectByType<MidiFilePlayer>();
    fp.MPTK_EffectSoundFont.EnableFilter = true;
    fp.MPTK_EffectSoundFont.FilterFreqOffset = 500;
    Plays a MIDI file from the MidiDB. This class must be used with the prefab MidiFilePlayer....
    Definition MidiFilePlayer.cs:69

◆ OnEventSynthAwake

EventSynthClass MidiPlayerTK.MidiSynth.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.

Example script (still recommended to set the callback from the inspector).

...
midiStreamPlayer.OnEventSynthAwake.AddListener(StartLoadingSynth);
...
public void StartLoadingSynth(string name)
{
Debug.LogFormat("Synth {0} loading", name);
}

◆ OnEventSynthStarted

EventSynthClass MidiPlayerTK.MidiSynth.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.

Example script (callback still recommended from the inspector).

public void EndLoadingSynth(string name)
{
Debug.Log($"EndLoadingSynth - Synth {name} loaded, now change bank and preset");
if (MAX_CHANNEL != 16)
// MIDI standard is limited to 16 channels.
// With MidiStream it's possible to extend channels number until 256.
// Warning: it's not possible to create MIDI file with channels number over 16.
midiStreamPlayer.MPTK_InitSynth(MAX_CHANNEL);
// Mandatory for updating UI list but not for playing sample.
// The default instrument and drum banks are defined with the popup "SoundFont Setup Alt-F" in the Unity editor.
// This method can be used by script to change the instrument bank and build presets available for it: MPTK_ListPreset.
midiStreamPlayer.MPTK_SoundFont.SelectBankInstrument(CurrentBank);
// Don't forget to initialize your MidiStreamPlayer variable, see link below:
// https://paxstellar.fr/api-mptk-v2/#DefinedVariablePrefab
// Channel 0: set Piano (if SoundFont is GeneralUser GS v1.471)
// Define bank with CurrentBank (value defined in inspector to 0).
midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent() { Command = MPTKCommand.ControlChange, Controller = MPTKController.BankSelectMsb, Value = CurrentBank, Channel = StreamChannel, });
Debug.LogFormat($" Bank '{CurrentBank}' defined on channel {StreamChannel}");
// Defined preset with CurrentPreset (value defined in inspector to 0).
midiStreamPlayer.MPTK_Channels[StreamChannel].PresetNum = CurrentPreset;
Debug.LogFormat($" Preset '{midiStreamPlayer.MPTK_Channels[StreamChannel].PresetName}' defined on channel {StreamChannel}");
// Playing a preset from another bank in the channel 1
// Channel 1: set Laser Gun (if SoundFont is GeneralUser GS v1.471)
// TBD int channel = 1, bank = 2, preset = 127;
//midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent() { Command = MPTKCommand.ControlChange, Controller = MPTKController.BankSelectMsb, Value = bank, Channel = channel, });
//midiStreamPlayer.MPTK_ChannelPresetChange(channel, preset);
// Before v2.10.1 Debug.LogFormat($" Preset '{MidiPlayerGlobal.MPTK_GetPatchName(bank, preset)}' defined on channel {channel} and bank {bank}");
}

◆ MPTK_OrientationToListener

float MidiPlayerTK.MidiSynth.MPTK_OrientationToListener

Returns the signed angle (in degrees) between the sound source and the AudioListener.

  • 0° = in front
  • +90° = right
  • -90° = left
  • ±180° = behind

Notes:

  • Convert to a 0–360° range with: MPTK_OrientationToListener < 0f ? MPTK_OrientationToListener + 360f : MPTK_OrientationToListener
  • When the source is exactly behind the listener, floating-point precision may cause the signed angle to be either +180° or -180°. After remapping to [0..360[, both cases consistently yield 180°.
Version
2.18.0 Pro

◆ MPTK_PauseOnMaxDistance

bool MidiPlayerTK.MidiSynth.MPTK_PauseOnMaxDistance = true

If true, the MIDI player will be automatically paused when the distance from the listener exceeds MPTK_MaxDistance.

Version
2.16.1

◆ OnMidiEvent

Func<MPTKEvent, bool> MidiPlayerTK.MidiSynth.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.

Acts as a MIDI event preprocessor: you can change MIDI values and therefore alter playback.
The callback receives an MPTKEvent object by reference (as it is a C# class).
See https://mptkapi.paxstellar.com/d9/d50/class_midi_player_t_k_1_1_m_p_t_k_event.html for the event structure.
You can change note, velocity, channel, skip events, or even change the MIDI message type.

Version
Maestro Pro
Note
  • The callback runs on a system thread, not the Unity main thread. Unity API calls are not allowed except Debug.Log (use sparingly).
  • Avoid heavy processing or waiting in the callback or timing accuracy will degrade.
  • The midiEvent is passed by reference. Re-instantiating it (midiEvent = new MPTKEvent()) or setting it to null has no effect.
  • MIDI position attributes (Tick and RealTime) can be read but changing them has no effect.
  • Changing a SetTempo event is too late for the sequencer (it has already been processed). Use midiFilePlayer.CurrentTempo to change tempo at runtime.
Example:
// See TestMidiFilePlayerScripting.cs for the demo.
void Start()
{
MidiFilePlayer midiFilePlayer = FindFirstObjectByType<MidiFilePlayer>();
midiFilePlayer.OnMidiEvent = PreProcessMidi;
}
// Example
bool PreProcessMidi(MPTKEvent midiEvent)
{
bool playEvent = true;
switch (midiEvent.Command)
{
case MPTKCommand.NoteOn:
if (midiEvent.Channel != 9)
// transpose 2 octaves
midiEvent.Value += 24;
else
// Drums are muted
playEvent = false;
break;
case MPTKCommand.PatchChange:
// Remove all patch changes: all channels will play the default preset 0
midiEvent.Command = MPTKCommand.MetaEvent;
midiEvent.Meta = MPTKMeta.TextEvent;
midiEvent.Info = "Patch Change removed";
break;
case MPTKCommand.MetaEvent:
if (midiEvent.Meta == MPTKMeta.SetTempo)
// Tempo forced to 100
midiFilePlayer.CurrentTempo = 100;
break;
}
// true: play this event, false to skip
return playEvent;
}
Represents a MIDI event used throughout MPTK. This class is central to script-based MIDI workflows in...
Definition MPTKEvent.cs:59
MPTKMeta Meta
Meta-event type when Command is MPTKCommand.MetaEvent (for example Lyric, TimeSignature,...
Definition MPTKEvent.cs:87
MPTKCommand Command
MIDI command type for this event. See MPTKCommand (NoteOn, ControlChange, PatchChange,...
Definition MPTKEvent.cs:73
int Channel
MIDI channel from 0 to 15 (channel 9 is typically used for drums).
Definition MPTKEvent.cs:155
MPTKMeta
MIDI meta event type. Meta events are optional MIDI information; none are mandatory....
Definition MPTKEnum.cs:325
MPTKCommand
MIDI command codes. Defines the action performed by the message: note on/off, patch change,...
Definition MPTKEnum.cs:16

◆ OnBeatEvent

Action<int, long, int, int> MidiPlayerTK.MidiSynth.OnBeatEvent

Invoked on each beat with the following parameters:

  • time: time in milliseconds since MIDI playback started.
  • tick: current tick.
  • measure: current measure (starts at 1).
  • beat: current beat (starts at 1).
    Note
  • OnBeatEvent is invoked on every beat, even if there is no MIDI event exactly on that beat.
  • Timing accuracy is guaranteed (runs on an internal thread).
  • Direct calls to the Unity API are not allowed, but Debug.Log and Maestro APIs (for example, playing a sound on each beat) are allowed.
    Version
    Maestro Pro
    // OnBeatEvent (pro) is triggered by the MPTK MIDI sequencer at each beat independently of MIDI events
    // - OnBeatEvent is executed at each beat even if there is there no MIDI event on the beat.
    // - Accuracy is guaranteed (internal thread).
    // - Direct call to Unity API is not possible (but you have access to all your script variables and most part of the MPTK API).
    // Parameters received:
    // - time Time in milliseconds since the start of the playing MIDI.
    // - tick Current tick of the beat.
    // - measure Current measure (start from 1).
    // - beat Current beat (start from 1).
    midiFilePlayer.OnBeatEvent = (int time, long tick, int measure, int beat) =>
    {
    if (FoldOutMetronome)
    {
    // Calculate the value to be displayed on the FoldOut Metronome and on the log
    beatTimeTick = $"Time: {TimeSpan.FromMilliseconds(time)} Tick: {tick}";
    beatMeasure = $"Beat/Measure: {beat}/{measure}";
    Debug.Log($"OnBeatEvent - {beatTimeTick} Signature segment:{midiFilePlayer.MPTK_MidiLoaded.MPTK_CurrentSignMap.Index} {beatMeasure}");
    // for testing interaction with Maestro MPTK player
    if (stopPlayingAtMeasure != -1 && measure >= stopPlayingAtMeasure)
    // Stops playback of the MIDI file. But the triggering event could be still playing (too late for stop it).
    midiFilePlayer.MPTK_Stop(false);
    // Plays an extra drum sound with each beat
    midiFilePlayer.MPTK_PlayDirectEvent(new MPTKEvent()
    {
    Command = MPTKCommand.NoteOn,
    Channel = 9,
    Value = instrumentMetronome,
    Velocity = volumeMetronome,
    Measure = measure,
    Beat = beat
    });
    }
    };

◆ MPTK_EffectUnity

MPTKEffectUnity MidiPlayerTK.MidiSynth.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.

Note
  • Unity effects integration modules are available only in Maestro MPTK Pro.
  • By default, these effects are disabled in Maestro.
  • Enable them from the prefab inspector: Synth Parameters / Unity Effect.
  • Each setting is also available by script.
Version
Maestro Pro
// Find an MPTK prefab; this will also work for MidiStreamPlayer, MidiExternalPlayer, and all classes that inherit from MidiSynth.
MidiFilePlayer fp = FindFirstObjectByType<MidiFilePlayer>();
fp.MPTK_EffectUnity.EnableReverb = true;
fp.MPTK_EffectUnity.ReverbDelay = 0.09f;

◆ MPTK_ModeSpatializer

ModeSpatializer MidiPlayerTK.MidiSynth.MPTK_ModeSpatializer

Current routing mode for MidiSpatializer (MIDI Spatial Mapper).

Version
Maestro Pro

◆ MPTK_MaxSpatialSynth

int MidiPlayerTK.MidiSynth.MPTK_MaxSpatialSynth

Gets or sets the maximum number of spatial synth instances that can be created/used by MidiSpatializer.

Version
Maestro Pro

◆ MPTK_SpatialSynthEnabled

bool MidiPlayerTK.MidiSynth.MPTK_SpatialSynthEnabled

In MidiSpatializer mode, not all MidiSynth instances are active.
True if this synth instance is currently enabled for spatial rendering.

Version
Maestro Pro

◆ MPTK_InstrumentNum

int MidiPlayerTK.MidiSynth.MPTK_InstrumentNum

In Track mode, contains the program number (preset) of the last instrument played.

Version
Maestro Pro

Property Documentation

◆ MPTK_Volume

float MidiPlayerTK.MidiSynth.MPTK_Volume
getset

Sets the global volume between 0 and 1 for the current MPTK Synth.

Note
:

◆ MPTK_Dsp64

bool MidiPlayerTK.MidiSynth.MPTK_Dsp64
getset

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).

Note
  • Bank 128 and preset 0 are generally used for drum kits.
Attention

◆ MPTK_ThreadMidiPriority

int MidiPlayerTK.MidiSynth.MPTK_ThreadMidiPriority
getset

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.

Note
A higher priority thread might consume all CPU time. It's recommended to set MPTK_ThreadMidiWait higher than 5 ms.

◆ MPTK_CorePlayer

bool MidiPlayerTK.MidiSynth.MPTK_CorePlayer
getset

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).

If true, MIDI events are read and played from a dedicated thread. If false, MidiSynth uses AudioSource GameObjects to play sound. This property must be set from the inspector before running the application. Default is true. Warning: the non-core mode player (MPTK_CorePlayer = false) will be removed in the next major version (V3).

◆ MPTK_StatVoiceCountSustained

int MidiPlayerTK.MidiSynth.MPTK_StatVoiceCountSustained
get

Gets the number of active voices currently in the sustained state.

A sustained voice typically indicates that a note is being held, such as when a sustain pedal is engaged or a note-on event has not yet been released. This property can be used to monitor sustained notes for performance analysis or MIDI event handling.

◆ MPTK_Orientation

bool MidiPlayerTK.MidiSynth.MPTK_Orientation
getset

Enables orientation-based audio behavior (Pro).

When enabled, MPTK applies directional audio processing based on the relative orientation between the sound source and the AudioListener.

This includes:

  • Smooth left/right stereo panning
  • Front/back volume attenuation
  • Subtle filtering when the sound source is behind the listener

Note: Enabling orientation-based audio may slightly reduce perceived loudness. Adjust the Global Volume setting if needed.

This feature is implemented internally by MPTK and does not require any external spatializer plugin.

The AudioListener used for orientation is defined by MPTK_AudioListener. By default, the first AudioListener found in the scene is used. You can override it from the inspector of the MidiPlayerGlobal prefab.

Version
2.18.0 Pro

◆ MPTK_DistanceAttenuation

bool MidiPlayerTK.MidiSynth.MPTK_DistanceAttenuation
getset

Enables Unity distance-based attenuation (min/max distance and custom rolloff curve). When enabled, MPTK configures the underlying AudioSource with:

  • minDistance
  • maxDistance
  • a custom rolloff curve
  • spatialBlend set to 3D (1.0)

This is a convenience helper for Unity's built-in 3D audio attenuation. It does not manage external spatializer plugins.

When disabled, MPTK does not modify the AudioSource. Configure Unity 3D audio settings directly on the AudioSource if needed, >especially when using an external spatializer plugin</b.

See setup details: https://paxstellar.fr/midi-file-player-detailed-view-2/#Foldout-Spatialization-Parameters

Notes:

  • Renamed from MPTK_Spatialize to MPTK_DistanceAttenuation in v2.18.0.
  • Can be combined with MPTK_Orientation (Pro) to apply angle-based panning and filtering.

◆ MPTK_IsSpatialSynthMaster

bool MidiPlayerTK.MidiSynth.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.

Version
Maestro Pro

◆ MPTK_InstrumentPlayed

string MidiPlayerTK.MidiSynth.MPTK_InstrumentPlayed
get

In Track mode, returns the name of the last instrument played on this track.
Empty string if unknown.

Version
Maestro Pro

◆ MPTK_TrackName

string MidiPlayerTK.MidiSynth.MPTK_TrackName
get

In Track mode, returns the last known track name.
Empty string if the MIDI file does not provide SequenceTrackName.

Version
Maestro Pro

Event Documentation

◆ OnAudioFrameStart

OnAudioFrameStartHandler MidiPlayerTK.MidiSynth.OnAudioFrameStart

Raised at the start of each audio frame by the audio engine.
.

The callback parameter is the current synth time, in milliseconds.
The callback does not run on the Unity main thread, so you must not call Unity APIs (except Debug.Log).

Version
Maestro Pro
// See Assets\MidiPlayer\Demo\ProDemos\Script\EuclideSeq\TestEuclideanRhythme.cs for the full code.
public void Play()
{
if (IsPlaying)
midiStream.OnAudioFrameStart += PlayHits;
else
midiStream.OnAudioFrameStart -= PlayHits;
}
private void PlayHits(double synthTimeMS)
{
if (lastSynthTime <= 0d)
// First call, initialize the last time
lastSynthTime = synthTimeMS;
// Time (ms) since the last callback
double deltaTime = synthTimeMS - lastSynthTime;
lastSynthTime = synthTimeMS;
timeMidiFromStartPlay += deltaTime;
// Time since last beat played
timeSinceLastBeat += deltaTime;
// Slider SldTempo in BPM.
// 60 BPM means 60 beats per minute: 1 beat per second, 1000 ms between beats.
// 120 BPM is twice as fast: 2 beats per second, 500 ms between beats.
// Delay between two quarter notes (ms)
CurrentTempo = (60d / SldTempo.Value) * 1000d;
// Is it time to play a hit?
if (IsPlaying && timeSinceLastBeat > CurrentTempo)
{
timeSinceLastBeat = 0d;
CurrentBeat++;
}
}