MidiPlayerTK.MidiFilePlayer

This class, associated to the prefab MidiFilePlayer, is able to play music from MIDI file.
MIDI files must be added from the Unity menu MPTK in the Unity editor.
There is no need to writing a script. For a simple usage, all the job can be done in the prefab inspector.
For more information see here https://paxstellar.fr/midi-file-player-detailed-view-2/
But for specific interactions, this class can be useful. Some use cases:
More...

+ Inheritance diagram for MidiPlayerTK.MidiFilePlayer:

Public Member Functions

int MPTK_ChannelBankGetIndex (int channel)
 Get the current bank associated to the channel.
Each MIDI channel can play a different preset and bank.
More...
 
int MPTK_ChannelCount ()
 Get channel length. The midi norm is 16, but MPTK can manage up to 32 channels (experimental). More...
 
bool MPTK_ChannelEnableGet (int channel)
 Is channel is enabled or disabled. More...
 
void MPTK_ChannelEnableSet (int channel, bool enable)
 Disable (mute) or enable (unmute) a MIDI channel. More...
 
int MPTK_ChannelForcedPresetGet (int channel)
 Set forced preset on the channel. MIDI will allways playing with this preset even if a MIDI Preset Change message is received.
Set to -1 to disable this behavior. More...
 
bool MPTK_ChannelForcedPresetSet (int channel, int preset, int bank=-1)
 Set a Preset on a channel to force the MIDI Synth to always playing with this instrument even if MIDI 'Preset Change' or 'Bank change' messages are received.
Set Preset to -1 to restore the Preset and Bank defined in the MIDI file. More...
 
string MPTK_ChannelInfo (int channel)
 Build an information string about the channel. It's also a good pretext to display an example of Channel API.
Exemple of return More...
 
int MPTK_ChannelNoteCount (int channel)
 Get count of notes played since the start of the MIDI. More...
 
bool MPTK_ChannelPresetChange (int channel, int preset, int bank=-1)
 Change the Preset and/or Bank associated to a Channel.
The new value of the bank or preset are registered in the channel even if the preset or bannk is not found.
Each channel can have a different bank/preset set.
Note 1: When bank is changed, the preset list is not updated (MidiPlayerGlobal.MPTK_ListPreset). Call MidiPlayerGlobal.MPTK_SelectBankInstrument to refresh this list.
Note 2: When playing a MIDI file, MIDI messages like "Patch Change" and "ControlChange BankSelectMsb" will override value registered with this method.
Note 3: To change globally the bank, use instead the global methods: MidiPlayerGlobal.MPTK_SelectBankInstrument or MidiPlayerGlobal.MPTK_SelectBankDrum.
Note 4: The method MPTK_ChannelForcedPresetSet can be used to force the preset whatever the MIDI messages.
More...
 
int MPTK_ChannelPresetGetIndex (int channel)
 Get channel preset index. More...
 
string MPTK_ChannelPresetGetName (int channel)
 Get the current preset name for the channel.
Each MIDI channel can play a different preset.
More...
 
float MPTK_ChannelVolumeGet (int channel)
 Get the volume of the channel More...
 
void MPTK_ChannelVolumeSet (int channel, float volume)
 Set the volume for a channel as a percentage. More...
 
void MPTK_ChorusSetDefault ()
 [MPTK PRO] - Set Chorus Unity default value as defined with Unity. More...
 
void MPTK_ClearAllSound (bool destroyAudioSource=false, int _idSession=-1)
 Clear all sound by sending note off.
That could take some seconds because release time for sample need to be played. More...
 
void MPTK_InitSynth (int channelCount=16)
 Initialize the synthetizer: channel, voices, modulator.
It's not usefull to call this method if you are using prefabs (MidiFilePlayer, MidiStreamPlayer, ...).
Each gameObjects created from these prefabs have their own, autonomous and isolated synth. More...
 
MidiLoad MPTK_Load ()
 Load the midi file defined with MPTK_MidiName or MPTK_MidiIndex. It's an optional action before playing a midi file witk MPTK_Play()
Use this method to get all MIDI events before start playing. More...
 
void MPTK_Next ()
 Play next MIDI from the list of midi defined in MPTK (see Unity menu Midi) More...
 
MPTKEvent.EnumLength MPTK_NoteLength (MPTKEvent note)
 Return note length as https://en.wikipedia.org/wiki/Note_value More...
 
void MPTK_Pause (float timeToPauseMS=-1f)
 Pause the current playing More...
 
virtual void MPTK_Play ()
 Play the midi file defined with MPTK_MidiName or MPTK_MidiIndex More...
 
virtual void MPTK_Play (float delayMillisecond)
 [MPTK PRO] Play the midi file defined with MPTK_MidiName or MPTK_MidiIndex with ramp-up to the volume defined with MPTK_Volume (0.5 by default) More...
 
void MPTK_Play (MidiFileWriter2 mfw2, float delayMillisecond=0f)
 [MPTK PRO] Play the midi from a MidiFileWriter2 object More...
 
void MPTK_PlayNextOrPrevious (int offset)
 [MPTK PRO] - Play next or previous Midi from the MidiDB list. More...
 
void MPTK_Previous ()
 Play previous MIDI from the list of midi defined in MPTK (see Unity menu Midi) More...
 
List< MPTKEventMPTK_ReadMidiEvents (long fromTicks=0, long toTicks=long.MaxValue)
 V2.88.2 - Read the list of midi events available in the MIDI from a ticks position to an end position. More...
 
void MPTK_RePlay ()
 Restart playing of the current midi file More...
 
void MPTK_ResetStat ()
 Reset voices statistics More...
 
void MPTK_ReverbSetDefault ()
 [MPTK PRO] - Set Reverb Unity default value as defined with Unity. More...
 
bool MPTK_SearchMidiToPlay (string name)
 [MPTK PRO] - Find a Midi in the Unity resources folder MidiDB which contains the name (case sensitive)
Tips: Add Midi files to your project with the Unity menu MPTK or add it directly in the ressource folder and open Midi File Setup to automatically integrate Midi in MPTK. More...
 
void MPTK_SFChorusSetDefault ()
 [MPTK PRO] - Set Chrous SoundFont default value as defined in fluidsynth.
FLUID_CHORUS_DEFAULT_N 3
FLUID_CHORUS_DEFAULT_LEVEL 2.0 but set to 0.9 (thank John)
FLUID_CHORUS_DEFAULT_SPEED 0.3
FLUID_CHORUS_DEFAULT_DEPTH 8.0
FLUID_CHORUS_DEFAULT_TYPE FLUID_CHORUS_MOD_SINE
WIDTH 10 More...
 
void MPTK_SFFilterSetDefault ()
 [MPTK PRO] - Set Filter SoundFont default value as defined in fluidsynth.
More...
 
void MPTK_SFReverbSetDefault ()
 [MPTK PRO] - Set Reverb SoundFont default value as defined in fluidsynth.
FLUID_REVERB_DEFAULT_ROOMSIZE 0.2f
FLUID_REVERB_DEFAULT_DAMP 0.0f
FLUID_REVERB_DEFAULT_WIDTH 0.5f
FLUID_REVERB_DEFAULT_LEVEL 0.9f
More...
 
void MPTK_StartSequencerMidi ()
 Start the MIDI sequencer: each midi events are read and play in a dedicated thread.
This thread is automatically started by prefabs MidiFilePlayer, MidiListPlayer, MidiExternalPlayer. More...
 
void MPTK_Stop ()
 Stop playing More...
 
virtual void MPTK_Stop (float delayMillisecond)
 [MPTK PRO] Stop playing within a delay. The volume decrease until the playing is stopped More...
 
void MPTK_StopSynth ()
 Stop processing samples by the synth and the MIDI sequencer. More...
 
void MPTK_SwitchMidiWithDelay (int index, string name, float volume, float delayToStopMillisecond, float delayToStartMillisecond)
 [MPTK PRO] Switch playing between two Midis with ramp-up.
This method is useful for an integration with Bolt: main Midi parameters are defined in one call. More...
 
void MPTK_UnPause ()
 UnPause the current playing More...
 
IEnumerator MPTK_WaitAllNotesOff (int _idSession=-1)
 Wait until all notes are off.
That could take some seconds due to the samples release time.
Therefore, the method exit after a timeout of 3 seconds.
*** Use this method only as a coroutine *** More...
 
delegate void OnAudioFrameStartHandler (double synthTime)
 Delegate for the event OnAudioFrameStartHandler. see OnAudioFrameStart More...
 

Public Attributes

bool MPTK_ApplyModLfo
 Apply LFO effect defined in the SoundFont More...
 
bool MPTK_ApplyRealTimeModulator
 Apply real time modulatoreffect defined in the SoundFont: pitch bend, control change, enveloppe modulation More...
 
bool MPTK_ApplySFChorus
 [MPTK PRO] - Apply chorus effect as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (10%). More...
 
bool MPTK_ApplySFFilter
 [MPTK PRO] - Apply frequency low-pass filter as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (40%). More...
 
bool MPTK_ApplySFReverb
 [MPTK PRO] - Apply reverberation effect as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (40%). More...
 
bool MPTK_ApplyVibLfo
 Apply vibrato effect defined in the SoundFont More...
 
bool MPTK_AudioSettingFromUnity
 If true then rate synth and buffer size will be automatically defined by Unity in accordance of the capacity of the hardware. - V2.89.0 -
Look at Unity menu "Edit / Project Settings..." and select between best latency and best performance.
If false, then rate and buffer size can be defined manually ... but with the risk of bad audio quality. It's more an experimental capacities! More...
 
bool MPTK_AutoBuffer = true
 Voice buffering is important to get better performance. But you can disable this fonction with this parameter. More...
 
int MPTK_AutoCleanVoiceLimit
 Free voices older than MPTK_AutoCleanVoiceLimit are removed when count is over than MPTK_AutoCleanVoiceTime More...
 
bool MPTK_CorePlayer
 If true then MIDI events are read and play from a dedicated thread.
If false, MidiSynth will use AudioSource gameobjects to play sound.
This properties must be defined before running the application from the inspector.
The default is true.
Warning: The non core mode player (MPTK_CorePlayer=false) will be removed with the next major version (V3) More...
 
float MPTK_CutOffVolume = 0.05f
 When amplitude is below this value the playing of sample is stopped (voice_off).
Can be increase for better performance but with degraded quality because sample could be stopped earlier. Remember: Amplitude can varying between 0 and 1. More...
 
bool MPTK_DirectSendToPlayer
 If true (default) then MIDI events are sent automatically to the midi player.
Set to false if you want to process events without playing sound.
OnEventNotesMidi Unity Event can be used to process each notes. More...
 
bool MPTK_EnableChangeTempo
 Should accept change tempo from MIDI Events ? More...
 
bool MPTK_EnableFreeSynthRate = false
 Allow direct setting of the Synth Rate More...
 
bool MPTK_EnablePanChange
 Should change pan from MIDI Events or from SoundFont ?
Pan is disabled when Spatialization is activated. More...
 
bool MPTK_EnablePresetDrum
 Should accept change Preset for Drum canal 10 ?
Disabled by default. Could sometimes create bad sound with midi files not really compliant with the MIDI norm. More...
 
bool MPTK_KillByExclusiveClass = true
 V2.83 Find the exclusive class of this voice. If set, kill all voices that match the exclusive class
and are younger than the first voice process created by this noteon event. More...
 
float MPTK_LeanSynthStarting = 0.05f
 V2.873 - A lean startup of the volume of the synth is useful to avoid weird sound at the beginning of the application (in some cases).
This parameter sets the speed of the increase of the volume of the audio source.
Set to 1 for an immediate full volume at start. More...
 
bool MPTK_LogWave
 Log for each wave to be played More...
 
bool MPTK_PauseOnFocusLoss
 Should the MIDI playing must be paused when the application lost the focus? More...
 
bool MPTK_ReleaseSameNote = true
 V2.83. If the same note is hit twice on the same channel, then the older voice process is advanced to the release stage.
It's the default Midi processing. More...
 
uint MPTK_ReleaseTimeMin = 500000
 [Only when CorePlayer=False] Define a minimum release time at noteoff in 100 iem nanoseconds.
Default 50 ms is a good tradeoff. Below some unpleasant sound could be heard. Useless when MPTK_CorePlayer is true. More...
 
float MPTK_ReleaseTimeMod = 1f
 When a note is stopped with a noteoff or when the duration is over, note continue to play for a short time depending the instrument.

This parameter is a multiplier to increase or decrease the default release time defined in the SoundFont for each instrument.
Recommended values between 0.1 and 10. Default is 1 (no modification of the release time).
Performance issue: the longer it lasts the more CPU is used after the noteon. With a long release time, a lot of samples will be played simultaneously. More...
 
bool MPTK_ResetChannel = true
 Reset channel information when MIDI start playing. V2.89.0 More...
 
float MPTK_SFChorusAmplify
 [MPTK PRO] - Chorus level is defined in the SoundFont in the range [0, 1].
This parameter is added to the the default SoundFont value.
Range must be [-1, 1] More...
 
float MPTK_SFFilterFreqOffset = 0f
 [MPTK PRO] - Frequency cutoff is defined in the SoundFont for each notes.
This parameter increase or decrease the default SoundFont value. Range: -2000 to 3000 More...
 
float MPTK_SFReverbAmplify
 [MPTK PRO] - Reverberation level is defined in the SoundFont in the range [0, 1].
This parameter is added to the the default SoundFont value.
Range must be [-1, 1] More...
 
bool MPTK_SpatialSynthEnabled
 In spatialization mode not all MidiSynths are enabled. More...
 
bool MPTK_StartPlayAtFirstNote
 When the value is true, the playing begins at the fisst note found
. Often, the first note is not defined at the beginning of the MIDI file (tick=0).
So there is a delay before playing the first note.
This setting is useful to start the playing at the first note found. Apply also when looping.
No impact on MPTK_Duration which stay the same, so there is a shift between the real time of the MIDI and the theoretical duration. More...
 
LoadingStatusMidiEnum MPTK_StatusLastMidiLoaded
 Status of the last midi loaded. The status is updated in a coroutine, so the status can change at each frame. More...
 
int MPTK_StatVoiceCountActive
 Count of the active voices (playing) - Readonly More...
 
int MPTK_StatVoiceCountFree
 Count of the free voices for reusing on need.
Voice older than AutoCleanVoiceTime are removed but only when count is over than AutoCleanVoiceLimit - Readonly More...
 
int MPTK_StatVoicePlayed
 Count of voice played since the start of the synth More...
 
float MPTK_StatVoiceRatioReused
 Percentage of voice reused during the synth life. 0: any reuse, 100:all voice reused (unattainable, of course!) More...
 
bool MPTK_WeakDevice
 Should play on a weak device (cheaper smartphone) ? Apply only with AudioSource mode (MPTK_CorePlayer=False).
Playing MIDI files with WeakDevice activated could cause some bad interpretation of MIDI Event, consequently bad sound. More...
 
EventEndMidiClass OnEventEndPlayMidi
 Define the Unity event to be triggered at end of playing the midi. More...
 
EventNotesMidiClass OnEventNotesMidi
 Define the Unity event to be triggered when notes are available from the MIDI file.
It's not possible to alter playing music by modifying note properties (pitch, velocity, ....) here. More...
 
EventStartMidiClass OnEventStartPlayMidi
 Define the Unity event to be triggered at start of playing the Midi. More...
 
EventSynthClass OnEventSynthAwake
 Unity event fired at awake of the synthesizer. Name of the gameobject component is passed as a parameter.
Setting this callback function by script (AddListener) is not recommended. It's better to set callback function from the inspector. More...
 
EventSynthClass OnEventSynthStarted
 Unity event fired at start of the synthesizer. Name of the gameobject component is passed as a parameter.
Setting this callback function by script (AddListener) is not recommended. It's better to set callback function from the inspector. More...
 
Action< MPTKEventOnMidiEvent
 [MPTK PRO] V2.89.0 - This function is called by the MIDI sequencer before sending the MIDI message to the MIDI synthesizer.
It can be used like a preprocessor of the MIDI events: it's possible to change the value of the MIDI events and therefore change the playback of the song.
The callback function receives a MPTKEvent object by reference (normal, it's a C# class) also everything is possible: change note, velocity, channel, ..., even changing the MIDI type of the message!!!
See below some examples of change.
Note 1: the callback is running on a system thread not on the Unity thread. Unity API call is not possible except for the Debug.Log (to be gently used, it consumes CPU)
Note 2: avoid heavy processing or waiting inside the callback otherwise MIDI playing accuracy will be bad.
Note 3: the midiEvent is passed by reference to the callback, so re-instanciate object (midiEvent = new MPTKEvent()) or set to null, has no effect!
Note 4: MIDI position attributs (Tick and RealTime) can be used in your algo but changing their values has no effect, it's too late!
More...
 
bool playOnlyFirstWave
 Preset are often composed with 2 or more samples, classically for left and right channel. Check this to play only the first sample found More...
 

Static Public Attributes

static List< MidiFilePlayerSpatialSynths
 Contains each MidiSynth for each channel or track when the prefab MidiSpatializer is used and IsMidiChannelSpace=true.
Warning: only one MidiSpatializer can be used in a hierarchy. More...
 

Properties

bool MPTK_ApplyUnityChorus [get, set]
 [MPTK PRO] - Apply Chorus Unity effect to the AudioSource. The effect is applied to all voices. More...
 
bool MPTK_ApplyUnityReverb [get, set]
 [MPTK PRO] - Apply Reverb Unity effect to the AudioSource. The effect is applied to all voices. More...
 
float MPTK_ChorusDelay [get, set]
 [MPTK PRO] - Chorus delay in ms.
Range from 0.1 to 100. Default = 40 ms. More...
 
float MPTK_ChorusDepth [get, set]
 [MPTK PRO] - Chorus modulation depth.
Range from 0 to 1. Default = 0.03. More...
 
float MPTK_ChorusDryMix [get, set]
 [MPTK PRO] - Volume of original signal to pass to output.
Range from 0 to 1. Default = 0.5. More...
 
float MPTK_ChorusRate [get, set]
 [MPTK PRO] - Chorus modulation rate in hz.
Range from 0 to 20. Default = 0.8 hz. More...
 
float MPTK_ChorusWetMix1 [get, set]
 [MPTK PRO] - Volume of 1st chorus tap.
Range from 0 to 1. Default = 0.5. More...
 
float MPTK_ChorusWetMix2 [get, set]
 [MPTK PRO] - Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap.
Range from 0 to 1. Default = 0.5. More...
 
float MPTK_ChorusWetMix3 [get, set]
 [MPTK PRO] - Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap.
Range from 0 to 1. Default = 0.5. More...
 
string? MPTK_Copyright [get]
 Get Copyright if defined in the MIDI file with MIDI MetaEventType = Copyright
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html More...
 
int MPTK_DeltaTicksPerQuarterNote [get]
 Delta Ticks Per Quarter Note. Indicate the duration time in "ticks" which make up a quarter-note.
For instance, if 96, then a duration of an eighth-note in the file would be 48.
More info here https://paxstellar.fr/2020/09/11/midi-timing/
More...
 
TimeSpan MPTK_Duration [get]
 Real duration expressed in TimeSpan of the full midi from the first event (tick=0) to the last event.
If MPTK_KeepEndTrack is false, the MIDI events End Track are not considered to calculate this time.
The tempo changes are taken into account if MPTK_EnableChangeTempo is set to true before loading the MIDI. More...
 
float MPTK_DurationMS [get]
 Real duration expressed in milliseconds of the full midi from the first event (tick=0) to the last event.
If MPTK_KeepEndTrack is false, the MIDI events End Track are not considered to calculate this time.
The tempo changes are taken into account if MPTK_EnableChangeTempo is set to true before loading the MIDI. More...
 
int MPTK_IndexSynthBuffSize [get, set]
 Set or Get synth buffer size -1:default, 0:64, 1;128, 2:256, 3:512, 4:1024, 5:2048.
The change is global for all prefab. It's better to stop playing for all prefab before changing on fly to avoid bad noise or crash. More...
 
int MPTK_IndexSynthRate [get, set]
 Set or Get sample rate output of the synth. -1:default, 0:24000, 1:36000, 2:48000, 3:60000, 4:72000, 5:84000, 6:96000.
It's better to stop playing before changing on fly to avoid bad noise. More...
 
string? MPTK_InstrumentPlayed [get]
 If spatialization is track mode, contains the last instrument played on this track More...
 
bool MPTK_IsPaused [get]
 Is MIDI file playing is paused ? More...
 
bool MPTK_IsPlaying [get]
 Is MIDI file is playing ? More...
 
bool MPTK_IsSpatialSynthMaster [get]
 Trus if this MidiSynth is the master synth responsible to read midi events and to dispatch to other MidiSynths More...
 
bool MPTK_KeepEndTrack [get, set]
 When set to true, meta MIDI event End Track are keep. Default is false.
If set to true, the End Track Event are taken into account for calculate the full duration of the MIDI.
See MPTK_DurationMS. More...
 
bool MPTK_KeepNoteOff [get, set]
 When the value is true, MIDI NoteOff events are keep from the MIDI file.
NoteOff in the stream have any impact on the MIDI synthesizer because
samples are stopped after a duration not from the NoteOff event. More...
 
bool MPTK_KeepPlayingNonLooped [get, set]
 V2.83 When the value is true, NoteOff and Duration for non-looped samples are ignored and the samples play through to the end. More...
 
MPTKEventMPTK_LastEventPlayed [get]
 Last MIDI event read or played More...
 
bool MPTK_LogEvents [get, set]
 Log midi events More...
 
bool MPTK_Loop [get, set]
 When the value is true, the playing is restarted when MIDI file reaches the end. The MIDI file doesn't need to be reloaded, the looping is almost immediate. More...
 
float MPTK_MaxDistance [get, set]
 If MPTK_Spatialize is enabled, the volume of the audio source depends on the distance between the audio source and the listener.
Beyong this distance, the volume is set to 0 and the midi player is paused. No effect if MPTK_Spatialize is disabled. More...
 
List< TrackMidiEvent >? MPTK_MidiEvents [get]
 [DEPRECATED] Get all the raw midi events available in the midi file.
Use rather the method MPTK_ReadMidiEvents from the prefab class MidiFileLoader or from MidiFilePrefab (Pro only). More...
 
int MPTK_MidiIndex [get, set]
 Select a MIDI file to play by its Index.
The Index of a MIDI file is displayed in the popup from the MidiFilePlayer inspector and in the window "Midi File Setup" from the MPTK menu in the editor.
More...
 
MidiLoad MPTK_MidiLoaded [get]
 Get detailed information about the MIDI playing. This readonly properties is available only when a MIDI is playing.
Rather use the method MPTK_Load() to get information about a MIDI before playing. V2.82. More...
 
virtual string MPTK_MidiName [get, set]
 Select a MIDI to play with its name.
Use the exact name as seen in the MIDI setup windows (Unity menu MPTK/ without any path or extension.
Tips: Add MIDI files to your project with the Unity menu MPTK. More...
 
bool MPTK_PauseOnDistance [get, set]
 [obsolete] replaced by MPTK_Spatialize"); V2.83 More...
 
bool MPTK_PlayOnStart [get, set]
 Should the MIDI start playing when application starts ? More...
 
TimeSpan MPTK_PlayTime [get]
 Time from the start of playing the current midi More...
 
double? MPTK_Position [get, set]
 Set or get the current position in the MIDI when playing in milliseconds. Warning: if you want to set the start position, set MPTK_Position inside the processing of the event OnEventStartPlayMidi because MPTK_Play() reset the start position to 0. Other possibility to change the position in the MIDI is to use the property MPTK_TickCurrent: set or get the position in tick More info here https://paxstellar.fr/2020/09/11/midi-timing/ More...
 
double? MPTK_PositionFirstNote [get]
 Real time position in millisecond for the first note-on found.
Most MIDI don't start playing a note immediately. There is often a delay.
Use this attribute to known the real time wich it will start.
See also MPTK_TickFirstNote More...
 
double? MPTK_PositionLastNote [get]
 Real time position in millisecond for the last note-on found in the MIDI.
There is often other MIDI events after the last note-on: for example event track-end.
Use this attribute to known the real time when all sound will be stop.
See also the MPTK_DurationMS which provides the full time of all MIDI events including track-end, control at the beginning and at the end, ....
See also MPTK_TickLastNote More...
 
string? MPTK_ProgramName [get]
 Get Program track name if defined in the MIDI file with MIDI MetaEventType = ProgramName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html More...
 
double MPTK_PulseLenght [get]
 Lenght in millisecond of a quarter. Obviously depends on the current tempo. More...
 
int MPTK_Quantization [get, set]
 Level of quantization : More...
 
double MPTK_RealTime [get]
 V2.89.0 - Real time in milliseconds from the beginning of playing of the MIDI.
MIDI Tempo or Speed change have no impact, it's just a system timer not linked to MIDI information. More...
 
float MPTK_ReverbDecayHFRatio [get, set]
 [MPTK PRO] - Decay HF Ratio : High-frequency to low-frequency decay time ratio.
Ranges from 0.1 to 2.0. More...
 
float MPTK_ReverbDecayTime [get, set]
 [MPTK PRO] - Reverberation decay time at low-frequencies in seconds.
Ranges from 0.1 to 20. Default is 1. More...
 
float MPTK_ReverbDelay [get, set]
 [MPTK PRO] - Late reverberation delay time relative to first reflection in seconds.
Ranges from 0 to 0.1. Default is 0.04 More...
 
float MPTK_ReverbDensity [get, set]
 [MPTK PRO] - Reverberation density (modal density) in percent.
Ranges from 0 to 1. More...
 
float MPTK_ReverbDiffusion [get, set]
 [MPTK PRO] - Reverberation diffusion (echo density) in percent.
Ranges from 0 to 1. Default is 1. More...
 
float MPTK_ReverbDryLevel [get, set]
 [MPTK PRO] - Mix level of dry signal in output.
Ranges from 0 to 1. More...
 
float MPTK_ReverbHFReference [get, set]
 [MPTK PRO] - Reference high frequency in Hz.
Ranges from 1000 to 20000. Default is 5000 More...
 
float MPTK_ReverbLevel [get, set]
 [MPTK PRO] - Late reverberation level relative to room effect.
Ranges from 0 to 1. More...
 
float MPTK_ReverbLFReference [get, set]
 [MPTK PRO] - Reference low-frequency in Hz.
Ranges from 20 to 1000. Default is 250 More...
 
float MPTK_ReverbReflectionDelay [get, set]
 [MPTK PRO] - Late reverberation level relative to room effect.
Ranges from -10000.0 to 2000.0. Default is 0.0. More...
 
float MPTK_ReverbReflectionLevel [get, set]
 [MPTK PRO] - Early reflections level relative to room effect.
Ranges from 0 to 1. More...
 
float MPTK_ReverbRoom [get, set]
 [MPTK PRO] - Room effect level at low frequencies.
Ranges from 0 to 1. More...
 
float MPTK_ReverbRoomHF [get, set]
 [MPTK PRO] - Room effect high-frequency level.
Ranges from 0 to 1. More...
 
float MPTK_ReverbRoomLF [get, set]
 [MPTK PRO] - Room effect low-frequency level.
Ranges from 0 to 1. More...
 
string? MPTK_SequenceTrackName [get]
 Get sequence track name if defined in the MIDI file with MIDI MetaEventType = SequenceTrackName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html More...
 
float MPTK_SFChorusDepth [get, set]
 [MPTK PRO] - Set the SoundFont chorus effect depth
Chorus depth [0, 256]
V2.88.2 More...
 
float MPTK_SFChorusLevel [get, set]
 [MPTK PRO] - Set the SoundFont chorus effect level [0, 10]
V2.88.2 - becomes a parameter and default value set to 0.9 (was 2f, thank John) More...
 
float MPTK_SFChorusSpeed [get, set]
 [MPTK PRO] - Set the SoundFont chorus effect speed
Chorus speed in Hz [0.1, 5]
V2.88.2 More...
 
float MPTK_SFChorusWidth [get, set]
 [MPTK PRO] - Set the SoundFont chorus effect width
The chorus unit process a monophonic input signal and produces stereo output controlled by WIDTH macro.
Width allows to get a gradually stereo effect from minimum (monophonic) to maximum stereo effect. [0, 10]
V2.88.2 More...
 
float MPTK_SFFilterQModOffset [get, set]
 [MPTK PRO] - Quality Factor is defined in the SoundFont for each notes.
This parameter increase or decrease the default SoundFont value. Range: -96 to 96. More...
 
float MPTK_SFReverbDamp [get, set]
 [MPTK PRO] - Set the SoundFont reverb effect damp [0,1].
Controls the reverb time frequency dependency. This controls the reverb time for the frequency sample rate/2
When 0, the reverb time for high frequencies is the same as for DC frequency.
When > 0, high frequencies have less reverb time than lower frequencies.
V2.88.2
More...
 
float MPTK_SFReverbLevel [get, set]
 [MPTK PRO] - Set the SoundFont reverb effect level
V2.88.2 More...
 
float MPTK_SFReverbRoomSize [get, set]
 [MPTK PRO] - Set the SoundFont reverb effect room size. Controls concave reverb time between 0 (0.7 s) and 1 (12.5 s)
V2.88.2
More...
 
float MPTK_SFReverbWidth [get, set]
 [MPTK PRO] - Set the SoundFont reverb effect width [0,100].
Controls the left/right output separation.
When 0, there are no separation and the signal on left and right output is the same.This sounds like a monophonic signal.
When 100, the separation between left and right is maximum.
V2.88.2
More...
 
bool MPTK_Spatialize [get, set]
 Should the Spatialization effect must be enabled?
See here how to setup spatialization with Unity https://paxstellar.fr/midi-file-player-detailed-view-2/#Foldout-Spatialization-Parameters More...
 
int MPTK_SpatialSynthIndex [get]
 Index of the MidiSynth for the dedicated Channel or Track when the prefab MidiSpatializer is used.
The MidiSynth reader (from a midi file) has no channel because no voice is played, so DedicatedChannel is set to -1 More...
 
float MPTK_Speed [get, set]
 Percentage value of the playing speed. Range 0.1 (10%) to 10 (1000%). Default is 1 for normal speed. More...
 
int MPTK_SynthRate [get, set]
 Get the the current synth rate or set free value (only if MPTK_EnableFreeSynthRate is true). More...
 
double MPTK_Tempo [get]
 Get the current tempo from the MIDI file (independent from MPTK_Speed). Return QuarterPerMinuteValue similar to BPM (Beat Per Measure) More...
 
string? MPTK_TextEvent [get]
 Get Text if defined in the MIDI file with MIDI MetaEventType = TextEvent
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html More...
 
long? MPTK_TickCurrent [get, set]
 Set or get the current tick position in the MIDI when playing.
MIDI tick is an easy way to identify a position in a song independently of the time which could vary with tempo change.
The count of ticks for a quarter is constant all along a Midi: see properties MPTK_DeltaTicksPerQuarterNote.
Example: with a time signature of 4/4 the ticks length of a bar is 4 * MPTK_DeltaTicksPerQuarterNote.
Warning: if you want to set the start position, set MPTK_TickCurrent inside the processing of the event OnEventStartPlayMidi
because MPTK_Play() reset the start position to 0.
Other possibility to change the position in the MIDI is to use the property MPTK_Position: set or get the position in milliseconds
but tempo change event will impact also this time.
More info here https://paxstellar.fr/2020/09/11/midi-timing/
More...
 
long? MPTK_TickFirstNote [get]
 Tick position for the first note-on found.
Most MIDI don't start playing a note immediately. There is often a delay.
Use this attribute to known the tick position where the will start to play a sound.
See also MPTK_PositionFirstNote More...
 
long? MPTK_TickLast [get]
 Last tick position in Midi: Value of the tick for the last MIDI event in sequence expressed in number of "ticks". MPTK_TickLast / MPTK_DeltaTicksPerQuarterNote equal the duration time of a quarter-note regardless the defined tempo. More...
 
long? MPTK_TickLastNote [get]
 Tick position for the last note-on found.
There is often other MIDI events after the last note-on: for example event track-end.
Use this attribute to known the tick position time when all sound will be stop.
See also the MPTK_PositionLastNote which provides the last tich of the MIDI. More...
 
int? MPTK_TrackCount [get]
 Count of track read in the MIDI file More...
 
string? MPTK_TrackInstrumentName [get]
 Get Instrument track name if defined in the MIDI file with MIDI MetaEventType = TrackInstrumentName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html More...
 
int MPTK_TransExcludedChannel [get, set]
 Transpose will apply to all channels except this one. Set to -1 to apply to all channel. V2.89.0
Default is 9 because generally we don't want to transpose drum channel. More...
 
int MPTK_Transpose [get, set]
 Transpose note from -24 to 24 More...
 
float MPTK_Volume [get, set]
 Global Volume. apply to all channels.
Must be >=0 and <= 1 More...
 

Events

OnAudioFrameStartHandler OnAudioFrameStart
 [MPTK PRO] - this event is triggered at each start of a new audio frame from the audio engine.
The parameter (double) is the current synth time in milliseconds. See example of use.
The callbach function will not run on the Unity thread, so you can't call Unity API except Debug.Log. More...
 

Detailed Description

This class, associated to the prefab MidiFilePlayer, is able to play music from MIDI file.
MIDI files must be added from the Unity menu MPTK in the Unity editor.
There is no need to writing a script. For a simple usage, all the job can be done in the prefab inspector.
For more information see here https://paxstellar.fr/midi-file-player-detailed-view-2/
But for specific interactions, this class can be useful. Some use cases:

// This example randomly select a MIDI to play.
using MidiPlayerTK; // Add a reference to the MPTK namespace at the top of your script
using UnityEngine;
public class YourClass : MonoBehaviour
{
// See TestMidiFilePlayerScripting.cs for a more detailed usage of this class.
public void RandomPlay()
{
// Need a reference to the prefab MidiFilePlayer that you have added in your scene hierarchy.
MidiFilePlayer midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
// Random select for the Midi
midiFilePlayer.MPTK_MidiIndex = UnityEngine.Random.Range(0, MidiPlayerGlobal.MPTK_ListMidi.Count);
// Play! How to make more simple?
midiFilePlayer.MPTK_Play();
}
}
Definition: MidiFileLoader.cs:11

Member Function Documentation

◆ MPTK_ChannelBankGetIndex()

int MidiPlayerTK.MidiSynth.MPTK_ChannelBankGetIndex ( int  channel)
inherited

Get the current bank associated to the channel.
Each MIDI channel can play a different preset and bank.

Parameters
channelMIDI channel must be between 0 and 15

◆ MPTK_ChannelCount()

int MidiPlayerTK.MidiSynth.MPTK_ChannelCount ( )
inherited

Get channel length. The midi norm is 16, but MPTK can manage up to 32 channels (experimental).

Parameters
channelmust be between 0 and 15
Returns
channel count

◆ MPTK_ChannelEnableGet()

bool MidiPlayerTK.MidiSynth.MPTK_ChannelEnableGet ( int  channel)
inherited

Is channel is enabled or disabled.

Parameters
channelchannel, must be between 0 and 15
Returns
true if channel is enabled

◆ MPTK_ChannelEnableSet()

void MidiPlayerTK.MidiSynth.MPTK_ChannelEnableSet ( int  channel,
bool  enable 
)
inherited

Disable (mute) or enable (unmute) a MIDI channel.

Parameters
channelmust be between 0 and 15
enabletrue to unmute (default), false to mute channel

◆ MPTK_ChannelForcedPresetGet()

int MidiPlayerTK.MidiSynth.MPTK_ChannelForcedPresetGet ( int  channel)
inherited

Set forced preset on the channel. MIDI will allways playing with this preset even if a MIDI Preset Change message is received.
Set to -1 to disable this behavior.

Parameters
channel
Returns
preset index, -1 if not set
GUILayout.Label($"{midiFilePlayer.MPTK_ChannelForcedPresetGet(channel)}/{midiFilePlayer.MPTK_ChannelBankGetIndex(channel)}");
int forced =
(int)GUILayout.HorizontalSlider(
midiFilePlayer.MPTK_ChannelForcedPresetGet(channel),
-1f, 127f);
if (forced != midiFilePlayer.MPTK_ChannelForcedPresetGet(channel))
midiFilePlayer.MPTK_ChannelForcedPresetSet(channel, forcedPreset);

◆ MPTK_ChannelForcedPresetSet()

bool MidiPlayerTK.MidiSynth.MPTK_ChannelForcedPresetSet ( int  channel,
int  preset,
int  bank = -1 
)
inherited

Set a Preset on a channel to force the MIDI Synth to always playing with this instrument even if MIDI 'Preset Change' or 'Bank change' messages are received.
Set Preset to -1 to restore the Preset and Bank defined in the MIDI file.

Parameters
channel0 to 15 channel
presetPreset to force in the range 0 to 127 preset. Set to -1 to restore the Preset and Bank known from the MIDI file.
bankOptionnal. Bank to force in the range 0 to 128. Set to -1 to restore to the last bank known from the MIDI file.
Returns
true if the preset/bank exists in the current SoudFont, otherwise false
// Example of changing the forced preset with the Unity GUI.
// ---------------------------------------------------------
int current = midiFilePlayer.MPTK_ChannelPresetGetIndex(channel);
// Slider to change the preset on this channel from -1 (disable forced) to 127
// The forced bank is defined from the inspector.
int forcePreset = (int)GUILayout.HorizontalSlider(current, -1f, 127f);
if (forcePreset != current)
{
// Force a preset and a bank whatever the MIDI events from the MIDI file.
midiFilePlayer.MPTK_ChannelForcedPresetSet(channel, forcePreset, forceBank);
}

Another example with MidiExternalPlayer.

// To force the preset from the start of the playing,
// the forced preset and the forced bank must be set
// after the MIDI is loaded and before any MIDI message is played.
// The OnEventStartPlayMidi event is perfect for that.
// ---------------------------------------------------------------
// Get the prefab added to the hierarchy of the current scene
MidiExternalPlayer midiPlayer = FindObjectOfType<MidiExternalPlayer>();
// Set the listener on the event OnEventStartPlayMidi
midiPlayer.OnEventStartPlayMidi.AddListener((string midiName) =>
{
// Each time the MIDI is started this script is runned
midiPlayer.MPTK_ChannelForcedPresetSet(0, 70, 1);
});

◆ MPTK_ChannelInfo()

string MidiPlayerTK.MidiSynth.MPTK_ChannelInfo ( int  channel)
inherited

Build an information string about the channel. It's also a good pretext to display an example of Channel API.
Exemple of return

  • Channel:2 Enabled [Preset:18, Bank:0] 'Rock Organ' Count:1 Volume:1
  • Channel:4 Muted [Preset:F44, Bank:0] 'Stereo Strings Trem' Count:33 Volume:0,50
Parameters
channelindex channel
Returns
Information string
GUILayout.BeginHorizontal();
GUILayout.Label("Channel Preset Preset / Bank Count Enabled Volume", myStyle.TitleLabel3);
GUILayout.EndHorizontal();
for (int channel = 0; channel < midiFilePlayer.MPTK_ChannelCount(); channel++)
{
GUILayout.BeginHorizontal();
// Display channel number and log info
if (GUILayout.Button($" {channel:00}", myStyle.TitleLabel3, GUILayout.Width(60)))
Debug.Log(midiFilePlayer.MPTK_ChannelInfo(channel));
// Display preset
GUILayout.Label(midiFilePlayer.MPTK_ChannelPresetGetName(channel) ?? "not set", myStyle.TitleLabel3, GUILayout.MaxWidth(150));
// Display preset and bank index
string sPreset = "";
int presetForced = midiFilePlayer.MPTK_ChannelForcedPresetGet(channel);
if (presetForced == -1)
{
// Preset not forced, get the preset defined on this channel by the Midi
sPreset = midiFilePlayer.MPTK_ChannelPresetGetIndex(channel).ToString();
}
else
{
sPreset = $"F{presetForced}";
}
int bankIndex = midiFilePlayer.MPTK_ChannelBankGetIndex(channel);
GUILayout.Label($"{sPreset} / {bankIndex}", myStyle.LabelRight/*, GUILayout.Width(80)*/);
int current = midiFilePlayer.MPTK_ChannelPresetGetIndex(channel);
// Slider to change the preset on this channel from -1 (disable forced) to 127.
// Forced bank from the inspector.
int forcePreset = (int)GUILayout.HorizontalSlider(current,
-1f, 127f, myStyle.SliderBar, myStyle.SliderThumb, GUILayout.Width(100));
if (forcePreset != current)
{
// 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.
midiFilePlayer.MPTK_ChannelForcedPresetSet(channel, forcePreset, forceBank);
}
// Display count note by channel
GUILayout.Label($"{midiFilePlayer.MPTK_ChannelNoteCount(channel),-5}", myStyle.LabelRight, GUILayout.Width(60));
// Toggle to enable or disable a channel
GUILayout.Label(" ", myStyle.TitleLabel3, GUILayout.Width(60));
bool state = GUILayout.Toggle(midiFilePlayer.MPTK_ChannelEnableGet(channel), "", GUILayout.MaxWidth(20));
if (state != midiFilePlayer.MPTK_ChannelEnableGet(channel))
{
midiFilePlayer.MPTK_ChannelEnableSet(channel, state);
Debug.LogFormat("Channel {0} state:{1}, preset:{2}", channel, state, midiFilePlayer.MPTK_ChannelPresetGetName(channel) ?? "not set"); /*2.84*/
}
// Slider to change volume
float currentVolume = midiFilePlayer.MPTK_ChannelVolumeGet(channel);
GUILayout.Label($"{Math.Round(currentVolume, 2)}", myStyle.LabelRight, GUILayout.Width(40));
float volume = GUILayout.HorizontalSlider(currentVolume, 0f, 1f, myStyle.SliderBar, myStyle.SliderThumb, GUILayout.Width(60));
if (volume != currentVolume)
{
midiFilePlayer.MPTK_ChannelVolumeSet(channel, volume);
}
GUILayout.EndHorizontal();
}

◆ MPTK_ChannelNoteCount()

int MidiPlayerTK.MidiSynth.MPTK_ChannelNoteCount ( int  channel)
inherited

Get count of notes played since the start of the MIDI.

Parameters
channelmust be between 0 and 15

◆ MPTK_ChannelPresetChange()

bool MidiPlayerTK.MidiSynth.MPTK_ChannelPresetChange ( int  channel,
int  preset,
int  bank = -1 
)
inherited

Change the Preset and/or Bank associated to a Channel.
The new value of the bank or preset are registered in the channel even if the preset or bannk is not found.
Each channel can have a different bank/preset set.
Note 1: When bank is changed, the preset list is not updated (MidiPlayerGlobal.MPTK_ListPreset). Call MidiPlayerGlobal.MPTK_SelectBankInstrument to refresh this list.
Note 2: When playing a MIDI file, MIDI messages like "Patch Change" and "ControlChange BankSelectMsb" will override value registered with this method.
Note 3: To change globally the bank, use instead the global methods: MidiPlayerGlobal.MPTK_SelectBankInstrument or MidiPlayerGlobal.MPTK_SelectBankDrum.
Note 4: The method MPTK_ChannelForcedPresetSet can be used to force the preset whatever the MIDI messages.

// Change bank or preset with free value with MPTK_ChannelPresetChange
// -------------------------------------------------------------------
// Select any value in the range 0 and 128 for the bank
int bank = (int)Slider("Free Bank", midiStreamPlayer.MPTK_ChannelBankGetIndex(StreamChannel), 0, 128, false, 100, 200);
// Select any value in the range 0 and 127 for the preset
int prst = (int)Slider("Free Preset", midiStreamPlayer.MPTK_ChannelPresetGetIndex(StreamChannel), 0, 127, true, 100, 200);
// If user made change for bank or preset ...
if (bank != midiStreamPlayer.MPTK_ChannelBankGetIndex(StreamChannel) ||
prst != midiStreamPlayer.MPTK_ChannelPresetGetIndex(StreamChannel))
{
// ... apply the change to the MidiStreamPlayer for the current channel.
// If the bank or the preset doestn't exist
// - the method returns false
// - the bank and preset are still registered in the channel
// - when a note-on is received on this channel, the first preset of the first bank is used to play (usually piano).
bool ret = midiStreamPlayer.MPTK_ChannelPresetChange(StreamChannel, prst, bank);
// Read the current bank, preset and preset name selected
int newbank = midiStreamPlayer.MPTK_ChannelBankGetIndex(StreamChannel);
int newpreset = midiStreamPlayer.MPTK_ChannelPresetGetIndex(StreamChannel);
string newname = midiStreamPlayer.MPTK_ChannelPresetGetName(StreamChannel);
Debug.Log($"MPTK_ChannelPresetChange result:{ret} bank:{newbank} preset:{newpreset} '{newname}'");
}
Parameters
channel0 to 15. There is 16 channels available in the MIDI norm.
presetThe total number of presets available depend on the soundfont selected
bankOptionnal, if not set or -1 the current bank will be applied (or default bank if never set). Default bank is defined globally: menu MPTK / SoundFont Setup.
Returns
true if the bank and the preset were found else false

◆ MPTK_ChannelPresetGetIndex()

int MidiPlayerTK.MidiSynth.MPTK_ChannelPresetGetIndex ( int  channel)
inherited

Get channel preset index.

Parameters
channelmust be between 0 and 15

◆ MPTK_ChannelPresetGetName()

string MidiPlayerTK.MidiSynth.MPTK_ChannelPresetGetName ( int  channel)
inherited

Get the current preset name for the channel.
Each MIDI channel can play a different preset.

Parameters
channelMIDI channel must be between 0 and 15

◆ MPTK_ChannelVolumeGet()

float MidiPlayerTK.MidiSynth.MPTK_ChannelVolumeGet ( int  channel)
inherited

Get the volume of the channel

Parameters
channelmust be between 0 and 15
Returns
volume of the channel, between 0 and 1

◆ MPTK_ChannelVolumeSet()

void MidiPlayerTK.MidiSynth.MPTK_ChannelVolumeSet ( int  channel,
float  volume 
)
inherited

Set the volume for a channel as a percentage.

Parameters
channelmust be between 0 and 15 or -1 to apply to all channel
volumepercentage of volume from the global volume for the channel, must be between 0 and 1

◆ MPTK_ChorusSetDefault()

void MidiPlayerTK.MidiSynth.MPTK_ChorusSetDefault ( )
inherited

[MPTK PRO] - Set Chorus Unity default value as defined with Unity.

◆ MPTK_ClearAllSound()

void MidiPlayerTK.MidiSynth.MPTK_ClearAllSound ( bool  destroyAudioSource = false,
int  _idSession = -1 
)
inherited

Clear all sound by sending note off.
That could take some seconds because release time for sample need to be played.

if (GUILayout.Button("Clear"))
midiStreamPlayer.MPTK_ClearAllSound(true);
Parameters
destroyAudioSourceusefull only in non core mode
_idSessionclear only for sample playing with this session, -1 for all (default)

◆ MPTK_InitSynth()

void MidiPlayerTK.MidiSynth.MPTK_InitSynth ( int  channelCount = 16)
inherited

Initialize the synthetizer: channel, voices, modulator.
It's not usefull to call this method if you are using prefabs (MidiFilePlayer, MidiStreamPlayer, ...).
Each gameObjects created from these prefabs have their own, autonomous and isolated synth.

Parameters
channelCountNumber of channel to create, default 16. Any other values are experimental!

◆ MPTK_Load()

MidiLoad MidiPlayerTK.MidiFilePlayer.MPTK_Load ( )

Load the midi file defined with MPTK_MidiName or MPTK_MidiIndex. It's an optional action before playing a midi file witk MPTK_Play()
Use this method to get all MIDI events before start playing.

private void GetMidiInfo()
{
MidiLoad midiloaded = midiFilePlayer.MPTK_Load();
if (midiloaded != null)
{
infoMidi = "Duration: " + midiloaded.MPTK_Duration.TotalSeconds + " seconds\n";
infoMidi += "Tempo: " + midiloaded.MPTK_InitialTempo + "\n";
List<MPTKEvent> listEvents = midiloaded.MPTK_ReadMidiEvents();
infoMidi += "Count MIDI Events: " + listEvents.Count + "\n";
Debug.Log(infoMidi);
}
}


Returns
MidiLoad to access all the properties of the midi loaded

◆ MPTK_Next()

void MidiPlayerTK.MidiFilePlayer.MPTK_Next ( )

Play next MIDI from the list of midi defined in MPTK (see Unity menu Midi)

◆ MPTK_NoteLength()

MPTKEvent.EnumLength MidiPlayerTK.MidiFilePlayer.MPTK_NoteLength ( MPTKEvent  note)

Return note length as https://en.wikipedia.org/wiki/Note_value

Parameters
note
Returns
MPTKEvent.EnumLength

◆ MPTK_Pause()

void MidiPlayerTK.MidiFilePlayer.MPTK_Pause ( float  timeToPauseMS = -1f)

Pause the current playing

Parameters
timeToPauseMStime to pause in milliseconds. default or < 0 : indefinitely

◆ MPTK_Play() [1/3]

virtual void MidiPlayerTK.MidiFilePlayer.MPTK_Play ( )
virtual

Play the midi file defined with MPTK_MidiName or MPTK_MidiIndex

Reimplemented in MidiPlayerTK.MidiExternalPlayer.

◆ MPTK_Play() [2/3]

virtual void MidiPlayerTK.MidiFilePlayer.MPTK_Play ( float  delayMillisecond)
virtual

[MPTK PRO] Play the midi file defined with MPTK_MidiName or MPTK_MidiIndex with ramp-up to the volume defined with MPTK_Volume (0.5 by default)

Parameters
delayMillisecondramp-up delay in milliseconds to get the default volume

◆ MPTK_Play() [3/3]

void MidiPlayerTK.MidiFilePlayer.MPTK_Play ( MidiFileWriter2  mfw2,
float  delayMillisecond = 0f 
)

[MPTK PRO] Play the midi from a MidiFileWriter2 object

Parameters
mfw2aMidiFileWriter2 object
delayMillisecond

◆ MPTK_PlayNextOrPrevious()

void MidiPlayerTK.MidiFilePlayer.MPTK_PlayNextOrPrevious ( int  offset)

[MPTK PRO] - Play next or previous Midi from the MidiDB list.

Parameters
offsetForward or backward count in the list. 1:the next, -1:the previous

◆ MPTK_Previous()

void MidiPlayerTK.MidiFilePlayer.MPTK_Previous ( )

Play previous MIDI from the list of midi defined in MPTK (see Unity menu Midi)

◆ MPTK_ReadMidiEvents()

List<MPTKEvent> MidiPlayerTK.MidiFilePlayer.MPTK_ReadMidiEvents ( long  fromTicks = 0,
long  toTicks = long.MaxValue 
)

V2.88.2 - Read the list of midi events available in the MIDI from a ticks position to an end position.

private void TheMostSimpleDemoForMidiPlayer()
{
MidiFilePlayer midiplayer = FindObjectOfType<MidiFilePlayer>();
if (midiplayer == null)
{
Debug.LogWarning("Can't find a MidiFilePlayer in the Hierarchy. Add a prefab MidiFileLoader.");
return;
}
// Index of the midi from the Midi DB (find it with 'Midi File Setup' from the menu MPTK)
midiplayer.MPTK_MidiIndex = 10;
// Open and load the Midi
midiplayer.MPTK_Load();
// Read midi event to a List<>
List<MPTKEvent> mptkEvents = midiplayer.MPTK_ReadMidiEvents();
// Loop on each Midi events
foreach (MPTKEvent mptkEvent in mptkEvents)
{
// Log if event is a note on
if (mptkEvent.Command == MPTKCommand.NoteOn)
Debug.Log($"Note on Time:{mptkEvent.RealTime} millisecond Note:{mptkEvent.Value} Duration:{mptkEvent.Duration} millisecond Velocity:{mptkEvent.Velocity}");
// Uncomment to display all Midi events
//Debug.Log(mptkEvent.ToString());
}
}
MPTKCommand
MIDI command codes. Defined the action to be done with the message: note on/off, change instrument,...
Definition: MPTKEvent.cs:15
Parameters
fromTicksticks start, default 0
toTicksticks end, default end of MIDI file
Returns

◆ MPTK_RePlay()

void MidiPlayerTK.MidiFilePlayer.MPTK_RePlay ( )

Restart playing of the current midi file

◆ MPTK_ResetStat()

void MidiPlayerTK.MidiSynth.MPTK_ResetStat ( )
inherited

Reset voices statistics

◆ MPTK_ReverbSetDefault()

void MidiPlayerTK.MidiSynth.MPTK_ReverbSetDefault ( )
inherited

[MPTK PRO] - Set Reverb Unity default value as defined with Unity.

◆ MPTK_SearchMidiToPlay()

bool MidiPlayerTK.MidiFilePlayer.MPTK_SearchMidiToPlay ( string  name)

[MPTK PRO] - Find a Midi in the Unity resources folder MidiDB which contains the name (case sensitive)
Tips: Add Midi files to your project with the Unity menu MPTK or add it directly in the ressource folder and open Midi File Setup to automatically integrate Midi in MPTK.

// Find the first Midi file name in MidiDB which contains "Adagio"
midiFilePlayer.MPTK_SearchMidiToPlay("Adagio");
// And play it
midiFilePlayer.MPTK_Play();
Parameters
namecase sensitive part of a midi file name
Returns
true if found else false

◆ MPTK_SFChorusSetDefault()

void MidiPlayerTK.MidiSynth.MPTK_SFChorusSetDefault ( )
inherited

[MPTK PRO] - Set Chrous SoundFont default value as defined in fluidsynth.
FLUID_CHORUS_DEFAULT_N 3
FLUID_CHORUS_DEFAULT_LEVEL 2.0 but set to 0.9 (thank John)
FLUID_CHORUS_DEFAULT_SPEED 0.3
FLUID_CHORUS_DEFAULT_DEPTH 8.0
FLUID_CHORUS_DEFAULT_TYPE FLUID_CHORUS_MOD_SINE
WIDTH 10

◆ MPTK_SFFilterSetDefault()

void MidiPlayerTK.MidiSynth.MPTK_SFFilterSetDefault ( )
inherited

[MPTK PRO] - Set Filter SoundFont default value as defined in fluidsynth.

◆ MPTK_SFReverbSetDefault()

void MidiPlayerTK.MidiSynth.MPTK_SFReverbSetDefault ( )
inherited

[MPTK PRO] - Set Reverb SoundFont default value as defined in fluidsynth.
FLUID_REVERB_DEFAULT_ROOMSIZE 0.2f
FLUID_REVERB_DEFAULT_DAMP 0.0f
FLUID_REVERB_DEFAULT_WIDTH 0.5f
FLUID_REVERB_DEFAULT_LEVEL 0.9f

Default chorus voice count

◆ MPTK_StartSequencerMidi()

void MidiPlayerTK.MidiSynth.MPTK_StartSequencerMidi ( )
inherited

Start the MIDI sequencer: each midi events are read and play in a dedicated thread.
This thread is automatically started by prefabs MidiFilePlayer, MidiListPlayer, MidiExternalPlayer.

◆ MPTK_Stop() [1/2]

void MidiPlayerTK.MidiFilePlayer.MPTK_Stop ( )

Stop playing

◆ MPTK_Stop() [2/2]

virtual void MidiPlayerTK.MidiFilePlayer.MPTK_Stop ( float  delayMillisecond)
virtual

[MPTK PRO] Stop playing within a delay. The volume decrease until the playing is stopped

Parameters
delayMilliseconddecrease time in millisconds

◆ MPTK_StopSynth()

void MidiPlayerTK.MidiSynth.MPTK_StopSynth ( )
inherited

Stop processing samples by the synth and the MIDI sequencer.

◆ MPTK_SwitchMidiWithDelay()

void MidiPlayerTK.MidiFilePlayer.MPTK_SwitchMidiWithDelay ( int  index,
string  name,
float  volume,
float  delayToStopMillisecond,
float  delayToStartMillisecond 
)

[MPTK PRO] Switch playing between two Midis with ramp-up.
This method is useful for an integration with Bolt: main Midi parameters are defined in one call.

Parameters
indexIndex of the Midi to play. Index is used only if no name is defined.
nameName of the Midi to play. Can be part of the Midi Name. If set, this parameter has priority over index parameter.
volumeVolume of the Midi. -1 to not change the default volume
delayToStopMillisecondDelay to stop the current midi playing (with volume decrease) or delay before playing the Midi if not Misi is playing
delayToStartMillisecondDelay to get the Midi at full volume (ramp-up volume)

◆ MPTK_UnPause()

void MidiPlayerTK.MidiFilePlayer.MPTK_UnPause ( )

UnPause the current playing

◆ MPTK_WaitAllNotesOff()

IEnumerator MidiPlayerTK.MidiSynth.MPTK_WaitAllNotesOff ( int  _idSession = -1)
inherited

Wait until all notes are off.
That could take some seconds due to the samples release time.
Therefore, the method exit after a timeout of 3 seconds.
*** 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 for samples playing with this session, -1 for all
Returns

◆ OnAudioFrameStartHandler()

delegate void MidiPlayerTK.MidiSynth.OnAudioFrameStartHandler ( double  synthTime)
inherited

Delegate for the event OnAudioFrameStartHandler. see OnAudioFrameStart

Parameters
synthTime

Member Data Documentation

◆ MPTK_ApplyModLfo

bool MidiPlayerTK.MidiSynth.MPTK_ApplyModLfo
inherited

Apply LFO effect defined in the SoundFont

◆ MPTK_ApplyRealTimeModulator

bool MidiPlayerTK.MidiSynth.MPTK_ApplyRealTimeModulator
inherited

Apply real time modulatoreffect defined in the SoundFont: pitch bend, control change, enveloppe modulation

◆ MPTK_ApplySFChorus

bool MidiPlayerTK.MidiSynth.MPTK_ApplySFChorus
inherited

[MPTK PRO] - Apply chorus effect as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (10%).

◆ MPTK_ApplySFFilter

bool MidiPlayerTK.MidiSynth.MPTK_ApplySFFilter
inherited

[MPTK PRO] - Apply frequency low-pass filter as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (40%).

◆ MPTK_ApplySFReverb

bool MidiPlayerTK.MidiSynth.MPTK_ApplySFReverb
inherited

[MPTK PRO] - Apply reverberation effect as defined in the SoundFont.
This effect is processed with the fluidsynth algo independently on each voices but with a small decrease of performace (40%).

◆ MPTK_ApplyVibLfo

bool MidiPlayerTK.MidiSynth.MPTK_ApplyVibLfo
inherited

Apply vibrato effect defined in the SoundFont

◆ MPTK_AudioSettingFromUnity

bool MidiPlayerTK.MidiSynth.MPTK_AudioSettingFromUnity
inherited

If true then rate synth and buffer size will be automatically defined by Unity in accordance of the capacity of the hardware. - V2.89.0 -
Look at Unity menu "Edit / Project Settings..." and select between best latency and best performance.
If false, then rate and buffer size can be defined manually ... but with the risk of bad audio quality. It's more an experimental capacities!

◆ MPTK_AutoBuffer

bool MidiPlayerTK.MidiSynth.MPTK_AutoBuffer = true
inherited

Voice buffering is important to get better performance. But you can disable this fonction with this parameter.

◆ MPTK_AutoCleanVoiceLimit

int MidiPlayerTK.MidiSynth.MPTK_AutoCleanVoiceLimit
inherited

Free voices older than MPTK_AutoCleanVoiceLimit are removed when count is over than MPTK_AutoCleanVoiceTime

◆ MPTK_CorePlayer

bool MidiPlayerTK.MidiSynth.MPTK_CorePlayer
inherited

If true then MIDI events are read and play from a dedicated thread.
If false, MidiSynth will use AudioSource gameobjects to play sound.
This properties must be defined before running the application from the inspector.
The default is true.
Warning: The non core mode player (MPTK_CorePlayer=false) will be removed with the next major version (V3)

◆ MPTK_CutOffVolume

float MidiPlayerTK.MidiSynth.MPTK_CutOffVolume = 0.05f
inherited

When amplitude is below this value the playing of sample is stopped (voice_off).
Can be increase for better performance but with degraded quality because sample could be stopped earlier. Remember: Amplitude can varying between 0 and 1.

◆ MPTK_DirectSendToPlayer

bool MidiPlayerTK.MidiSynth.MPTK_DirectSendToPlayer
inherited

If true (default) then MIDI events are sent automatically to the midi player.
Set to false if you want to process events without playing sound.
OnEventNotesMidi Unity Event can be used to process each notes.

◆ MPTK_EnableChangeTempo

bool MidiPlayerTK.MidiSynth.MPTK_EnableChangeTempo
inherited

Should accept change tempo from MIDI Events ?

◆ MPTK_EnableFreeSynthRate

bool MidiPlayerTK.MidiSynth.MPTK_EnableFreeSynthRate = false
inherited

Allow direct setting of the Synth Rate

◆ MPTK_EnablePanChange

bool MidiPlayerTK.MidiSynth.MPTK_EnablePanChange
inherited

Should change pan from MIDI Events or from SoundFont ?
Pan is disabled when Spatialization is activated.

◆ MPTK_EnablePresetDrum

bool MidiPlayerTK.MidiSynth.MPTK_EnablePresetDrum
inherited

Should accept change Preset for Drum canal 10 ?
Disabled by default. Could sometimes create bad sound with midi files not really compliant with the MIDI norm.

◆ MPTK_KillByExclusiveClass

bool MidiPlayerTK.MidiSynth.MPTK_KillByExclusiveClass = true
inherited

V2.83 Find the exclusive class of this voice. If set, kill all voices that match the exclusive class
and are younger than the first voice process created by this noteon event.

◆ MPTK_LeanSynthStarting

float MidiPlayerTK.MidiSynth.MPTK_LeanSynthStarting = 0.05f
inherited

V2.873 - A lean startup of the volume of the synth is useful to avoid weird sound at the beginning of the application (in some cases).
This parameter sets the speed of the increase of the volume of the audio source.
Set to 1 for an immediate full volume at start.

◆ MPTK_LogWave

bool MidiPlayerTK.MidiSynth.MPTK_LogWave
inherited

Log for each wave to be played

◆ MPTK_PauseOnFocusLoss

bool MidiPlayerTK.MidiFilePlayer.MPTK_PauseOnFocusLoss

Should the MIDI playing must be paused when the application lost the focus?

◆ MPTK_ReleaseSameNote

bool MidiPlayerTK.MidiSynth.MPTK_ReleaseSameNote = true
inherited

V2.83. If the same note is hit twice on the same channel, then the older voice process is advanced to the release stage.
It's the default Midi processing.

◆ MPTK_ReleaseTimeMin

uint MidiPlayerTK.MidiSynth.MPTK_ReleaseTimeMin = 500000
inherited

[Only when CorePlayer=False] Define a minimum release time at noteoff in 100 iem nanoseconds.
Default 50 ms is a good tradeoff. Below some unpleasant sound could be heard. Useless when MPTK_CorePlayer is true.

◆ MPTK_ReleaseTimeMod

float MidiPlayerTK.MidiSynth.MPTK_ReleaseTimeMod = 1f
inherited

When a note is stopped with a noteoff or when the duration is over, note continue to play for a short time depending the instrument.

This parameter is a multiplier to increase or decrease the default release time defined in the SoundFont for each instrument.
Recommended values between 0.1 and 10. Default is 1 (no modification of the release time).
Performance issue: the longer it lasts the more CPU is used after the noteon. With a long release time, a lot of samples will be played simultaneously.

◆ MPTK_ResetChannel

bool MidiPlayerTK.MidiSynth.MPTK_ResetChannel = true
inherited

Reset channel information when MIDI start playing. V2.89.0

◆ MPTK_SFChorusAmplify

float MidiPlayerTK.MidiSynth.MPTK_SFChorusAmplify
inherited

[MPTK PRO] - Chorus level is defined in the SoundFont in the range [0, 1].
This parameter is added to the the default SoundFont value.
Range must be [-1, 1]

◆ MPTK_SFFilterFreqOffset

float MidiPlayerTK.MidiSynth.MPTK_SFFilterFreqOffset = 0f
inherited

[MPTK PRO] - Frequency cutoff is defined in the SoundFont for each notes.
This parameter increase or decrease the default SoundFont value. Range: -2000 to 3000

◆ MPTK_SFReverbAmplify

float MidiPlayerTK.MidiSynth.MPTK_SFReverbAmplify
inherited

[MPTK PRO] - Reverberation level is defined in the SoundFont in the range [0, 1].
This parameter is added to the the default SoundFont value.
Range must be [-1, 1]

◆ MPTK_SpatialSynthEnabled

bool MidiPlayerTK.MidiSynth.MPTK_SpatialSynthEnabled
inherited

In spatialization mode not all MidiSynths are enabled.

◆ MPTK_StartPlayAtFirstNote

bool MidiPlayerTK.MidiFilePlayer.MPTK_StartPlayAtFirstNote

When the value is true, the playing begins at the fisst note found
. Often, the first note is not defined at the beginning of the MIDI file (tick=0).
So there is a delay before playing the first note.
This setting is useful to start the playing at the first note found. Apply also when looping.
No impact on MPTK_Duration which stay the same, so there is a shift between the real time of the MIDI and the theoretical duration.

◆ MPTK_StatusLastMidiLoaded

LoadingStatusMidiEnum MidiPlayerTK.MidiFilePlayer.MPTK_StatusLastMidiLoaded

Status of the last midi loaded. The status is updated in a coroutine, so the status can change at each frame.

◆ MPTK_StatVoiceCountActive

int MidiPlayerTK.MidiSynth.MPTK_StatVoiceCountActive
inherited

Count of the active voices (playing) - Readonly

◆ MPTK_StatVoiceCountFree

int MidiPlayerTK.MidiSynth.MPTK_StatVoiceCountFree
inherited

Count of the free voices for reusing on need.
Voice older than AutoCleanVoiceTime are removed but only when count is over than AutoCleanVoiceLimit - Readonly

◆ MPTK_StatVoicePlayed

int MidiPlayerTK.MidiSynth.MPTK_StatVoicePlayed
inherited

Count of voice played since the start of the synth

◆ MPTK_StatVoiceRatioReused

float MidiPlayerTK.MidiSynth.MPTK_StatVoiceRatioReused
inherited

Percentage of voice reused during the synth life. 0: any reuse, 100:all voice reused (unattainable, of course!)

◆ MPTK_WeakDevice

bool MidiPlayerTK.MidiSynth.MPTK_WeakDevice
inherited

Should play on a weak device (cheaper smartphone) ? Apply only with AudioSource mode (MPTK_CorePlayer=False).
Playing MIDI files with WeakDevice activated could cause some bad interpretation of MIDI Event, consequently bad sound.

◆ OnEventEndPlayMidi

EventEndMidiClass MidiPlayerTK.MidiFilePlayer.OnEventEndPlayMidi

Define the Unity event to be triggered at end of playing the midi.

using MidiPlayerTK; // Add a reference to the MPTK namespace at the top of your script
using UnityEngine;
public class YourClass : MonoBehaviour
{
MidiFilePlayer midiFilePlayer;
void Start()
{
// Get a reference to the prefab MidiFilePlayer from the hierarchy in the scene
midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
// Add a listener on the MIDI File Player.
// NotesToPlay will be called for each new group of notes read by the MIDI sequencer from the MIDI file.
midiFilePlayer.OnEventEndPlayMidi.AddListener(EndPlay);
}
public void EndPlay(string midiname, EventEndMidiEnum reason)
{
Debug.LogFormat($"End playing midi {midiname} reason:{reason}");
}
}

◆ OnEventNotesMidi

EventNotesMidiClass MidiPlayerTK.MidiFilePlayer.OnEventNotesMidi

Define the Unity event to be triggered when notes are available from the MIDI file.
It's not possible to alter playing music by modifying note properties (pitch, velocity, ....) here.

using MidiPlayerTK; // Add a reference to the MPTK namespace at the top of your script
using UnityEngine;
public class YourClass : MonoBehaviour
{
MidiFilePlayer midiFilePlayer;
void Start()
{
// Get a reference to the prefab MidiFilePlayer from the hierarchy in the scene
midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
// Add a listener on the MIDI File Player.
// NotesToPlay will be called for each new group of notes read by the MIDI sequencer from the MIDI file.
midiFilePlayer.OnEventNotesMidi.AddListener(NotesToPlay);
}
// This method will be called by the MIDI sequencer just before the notes
// are playing by the MIDI synthesizer (if 'Send To Synth' is enabled)
public void NotesToPlay(List<MPTKEvent> mptkEvents)
{
Debug.Log("Received " + mptkEvents.Count + " MIDI Events");
// Loop on each MIDI events
foreach (MPTKEvent mptkEvent in mptkEvents)
{
// Log if event is a note on
if (mptkEvent.Command == MPTKCommand.NoteOn)
Debug.Log($"Note on Time:{mptkEvent.RealTime} millisecond Note:{mptkEvent.Value} Duration:{mptkEvent.Duration} millisecond Velocity:{mptkEvent.Velocity}");
// Uncomment to display all MIDI events
// Debug.Log(mptkEvent.ToString());
}
}
}

◆ OnEventStartPlayMidi

EventStartMidiClass MidiPlayerTK.MidiFilePlayer.OnEventStartPlayMidi

Define the Unity event to be triggered at start of playing the Midi.

using MidiPlayerTK; // Add a reference to the MPTK namespace at the top of your script
using UnityEngine;
public class YourClass : MonoBehaviour
{
MidiFilePlayer midiFilePlayer;
void Start()
{
// Get a reference to the prefab MidiFilePlayer from the hierarchy in the scene
midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
// Add a listener on the MIDI File Player.
// NotesToPlay will be called for each new group of notes read by the MIDI sequencer from the MIDI file.
midiFilePlayer.OnEventStartPlayMidi.AddListener(StartPlay);
}
public void StartPlay(string midiname)
{
Debug.LogFormat($"Start playing midi {midiname}");
}
}

◆ OnEventSynthAwake

EventSynthClass MidiPlayerTK.MidiSynth.OnEventSynthAwake
inherited

Unity event fired at awake of the synthesizer. Name of the gameobject component is passed as a parameter.
Setting this callback function by script (AddListener) is not recommended. It's better to set callback function from the inspector.

Example of script (but it's recommended to set callback function from the inspector).

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

◆ OnEventSynthStarted

EventSynthClass MidiPlayerTK.MidiSynth.OnEventSynthStarted
inherited

Unity event fired at start of the synthesizer. Name of the gameobject component is passed as a parameter.
Setting this callback function by script (AddListener) is not recommended. It's better to set callback function from the inspector.

Example of script (it's recommended to set callback function from the inspector).

public void EndLoadingSynth(string name)
{
Debug.LogFormat($"Synth {name} loaded, now change bank and preset");
// It's recommended to defined callback method (here EndLoadingSynth) in the prefab MidiStreamPlayer from the Unity editor inspector.
// EndLoadingSynth will be called when the synthesizer will be ready.
// These calls will not work in Unity Awake() or Startup() because Midi synth must be ready when changing preset and/or bank.
// 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.
MidiPlayerGlobal.MPTK_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_ChannelPresetChange(StreamChannel, CurrentPreset);
Debug.LogFormat($" Preset '{midiStreamPlayer.MPTK_ChannelPresetGetName(0)}' 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)
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);
// MPTK_GetPatchName mandatory for getting the patch nane when the bank is not the default bank.
Debug.LogFormat($" Preset '{MidiPlayerGlobal.MPTK_GetPatchName(bank, preset)}' defined on channel {channel} and bank {bank}");
}
MPTKController
MidiController enumeration http://www.midi.org/techspecs/midimessages.php#3
Definition: MPTKEvent.cs:123

◆ OnMidiEvent

Action<MPTKEvent> MidiPlayerTK.MidiSynth.OnMidiEvent
inherited

[MPTK PRO] V2.89.0 - This function is called by the MIDI sequencer before sending the MIDI message to the MIDI synthesizer.
It can be used like a preprocessor of the MIDI events: it's possible to change the value of the MIDI events and therefore change the playback of the song.
The callback function receives a MPTKEvent object by reference (normal, it's a C# class) also everything is possible: change note, velocity, channel, ..., even changing the MIDI type of the message!!!
See below some examples of change.
Note 1: the callback is running on a system thread not on the Unity thread. Unity API call is not possible except for the Debug.Log (to be gently used, it consumes CPU)
Note 2: avoid heavy processing or waiting inside the callback otherwise MIDI playing accuracy will be bad.
Note 3: the midiEvent is passed by reference to the callback, so re-instanciate object (midiEvent = new MPTKEvent()) or set to null, has no effect!
Note 4: MIDI position attributs (Tick and RealTime) can be used in your algo but changing their values has no effect, it's too late!

// See TestMidiFilePlayerScripting.cs for the demo.
void Start()
{
MidiFilePlayer midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
midiFilePlayer.OnMidiEvent = PreProcessMidi;
}
// Some example
void PreProcessMidi(MPTKEvent midiEvent)
{
switch (midiEvent.Command)
{
case MPTKCommand.NoteOn:
if (midiEvent.Channel != 9)
// transpose 2 octaves
midiEvent.Value += 24;
else
// Drums are muted
midiEvent.Velocity = 0;
break;
case MPTKCommand.PatchChange:
// Remove all patch change: all channels will played the default preset 0!!!
midiEvent.Command = MPTKCommand.MetaEvent;
midiEvent.Meta = MPTKMeta.TextEvent;
midiEvent.Info = "Patch Change removed";
break;
}
}
MPTKMeta
MIDI MetaEvent Type
Definition: MPTKEvent.cs:302

◆ playOnlyFirstWave

bool MidiPlayerTK.MidiSynth.playOnlyFirstWave
inherited

Preset are often composed with 2 or more samples, classically for left and right channel. Check this to play only the first sample found


◆ SpatialSynths

List<MidiFilePlayer> MidiPlayerTK.MidiSynth.SpatialSynths
staticinherited

Contains each MidiSynth for each channel or track when the prefab MidiSpatializer is used and IsMidiChannelSpace=true.
Warning: only one MidiSpatializer can be used in a hierarchy.

Property Documentation

◆ MPTK_ApplyUnityChorus

bool MidiPlayerTK.MidiSynth.MPTK_ApplyUnityChorus
getsetinherited

[MPTK PRO] - Apply Chorus Unity effect to the AudioSource. The effect is applied to all voices.

◆ MPTK_ApplyUnityReverb

bool MidiPlayerTK.MidiSynth.MPTK_ApplyUnityReverb
getsetinherited

[MPTK PRO] - Apply Reverb Unity effect to the AudioSource. The effect is applied to all voices.

◆ MPTK_ChorusDelay

float MidiPlayerTK.MidiSynth.MPTK_ChorusDelay
getsetinherited

[MPTK PRO] - Chorus delay in ms.
Range from 0.1 to 100. Default = 40 ms.

◆ MPTK_ChorusDepth

float MidiPlayerTK.MidiSynth.MPTK_ChorusDepth
getsetinherited

[MPTK PRO] - Chorus modulation depth.
Range from 0 to 1. Default = 0.03.

◆ MPTK_ChorusDryMix

float MidiPlayerTK.MidiSynth.MPTK_ChorusDryMix
getsetinherited

[MPTK PRO] - Volume of original signal to pass to output.
Range from 0 to 1. Default = 0.5.

◆ MPTK_ChorusRate

float MidiPlayerTK.MidiSynth.MPTK_ChorusRate
getsetinherited

[MPTK PRO] - Chorus modulation rate in hz.
Range from 0 to 20. Default = 0.8 hz.

◆ MPTK_ChorusWetMix1

float MidiPlayerTK.MidiSynth.MPTK_ChorusWetMix1
getsetinherited

[MPTK PRO] - Volume of 1st chorus tap.
Range from 0 to 1. Default = 0.5.

◆ MPTK_ChorusWetMix2

float MidiPlayerTK.MidiSynth.MPTK_ChorusWetMix2
getsetinherited

[MPTK PRO] - Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap.
Range from 0 to 1. Default = 0.5.

◆ MPTK_ChorusWetMix3

float MidiPlayerTK.MidiSynth.MPTK_ChorusWetMix3
getsetinherited

[MPTK PRO] - Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap.
Range from 0 to 1. Default = 0.5.

◆ MPTK_Copyright

string? MidiPlayerTK.MidiFilePlayer.MPTK_Copyright
get

Get Copyright if defined in the MIDI file with MIDI MetaEventType = Copyright
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html

◆ MPTK_DeltaTicksPerQuarterNote

int MidiPlayerTK.MidiFilePlayer.MPTK_DeltaTicksPerQuarterNote
get

Delta Ticks Per Quarter Note. Indicate the duration time in "ticks" which make up a quarter-note.
For instance, if 96, then a duration of an eighth-note in the file would be 48.
More info here https://paxstellar.fr/2020/09/11/midi-timing/

Move forward one quarter
midiFilePlayer.MPTK_TickCurrent = midiFilePlayer.MPTK_TickCurrent + midiFilePlayer.MPTK_DeltaTicksPerQuarterNote;

◆ MPTK_Duration

TimeSpan MidiPlayerTK.MidiFilePlayer.MPTK_Duration
get

Real duration expressed in TimeSpan of the full midi from the first event (tick=0) to the last event.
If MPTK_KeepEndTrack is false, the MIDI events End Track are not considered to calculate this time.
The tempo changes are taken into account if MPTK_EnableChangeTempo is set to true before loading the MIDI.

◆ MPTK_DurationMS

float MidiPlayerTK.MidiFilePlayer.MPTK_DurationMS
get

Real duration expressed in milliseconds of the full midi from the first event (tick=0) to the last event.
If MPTK_KeepEndTrack is false, the MIDI events End Track are not considered to calculate this time.
The tempo changes are taken into account if MPTK_EnableChangeTempo is set to true before loading the MIDI.

◆ MPTK_IndexSynthBuffSize

int MidiPlayerTK.MidiSynth.MPTK_IndexSynthBuffSize
getsetinherited

Set or Get synth buffer size -1:default, 0:64, 1;128, 2:256, 3:512, 4:1024, 5:2048.
The change is global for all prefab. It's better to stop playing for all prefab before changing on fly to avoid bad noise or crash.

◆ MPTK_IndexSynthRate

int MidiPlayerTK.MidiSynth.MPTK_IndexSynthRate
getsetinherited

Set or Get sample rate output of the synth. -1:default, 0:24000, 1:36000, 2:48000, 3:60000, 4:72000, 5:84000, 6:96000.
It's better to stop playing before changing on fly to avoid bad noise.

◆ MPTK_InstrumentPlayed

string? MidiPlayerTK.MidiSynth.MPTK_InstrumentPlayed
getinherited

If spatialization is track mode, contains the last instrument played on this track

◆ MPTK_IsPaused

bool MidiPlayerTK.MidiFilePlayer.MPTK_IsPaused
get

Is MIDI file playing is paused ?

◆ MPTK_IsPlaying

bool MidiPlayerTK.MidiFilePlayer.MPTK_IsPlaying
get

Is MIDI file is playing ?

◆ MPTK_IsSpatialSynthMaster

bool MidiPlayerTK.MidiSynth.MPTK_IsSpatialSynthMaster
getinherited

Trus if this MidiSynth is the master synth responsible to read midi events and to dispatch to other MidiSynths

◆ MPTK_KeepEndTrack

bool MidiPlayerTK.MidiFilePlayer.MPTK_KeepEndTrack
getset

When set to true, meta MIDI event End Track are keep. Default is false.
If set to true, the End Track Event are taken into account for calculate the full duration of the MIDI.
See MPTK_DurationMS.

◆ MPTK_KeepNoteOff

bool MidiPlayerTK.MidiFilePlayer.MPTK_KeepNoteOff
getset

When the value is true, MIDI NoteOff events are keep from the MIDI file.
NoteOff in the stream have any impact on the MIDI synthesizer because
samples are stopped after a duration not from the NoteOff event.

◆ MPTK_KeepPlayingNonLooped

bool MidiPlayerTK.MidiSynth.MPTK_KeepPlayingNonLooped
getsetinherited

V2.83 When the value is true, NoteOff and Duration for non-looped samples are ignored and the samples play through to the end.

◆ MPTK_LastEventPlayed

MPTKEvent? MidiPlayerTK.MidiFilePlayer.MPTK_LastEventPlayed
get

Last MIDI event read or played

◆ MPTK_LogEvents

bool MidiPlayerTK.MidiFilePlayer.MPTK_LogEvents
getset

Log midi events

◆ MPTK_Loop

bool MidiPlayerTK.MidiFilePlayer.MPTK_Loop
getset

When the value is true, the playing is restarted when MIDI file reaches the end. The MIDI file doesn't need to be reloaded, the looping is almost immediate.

◆ MPTK_MaxDistance

float MidiPlayerTK.MidiSynth.MPTK_MaxDistance
getsetinherited

If MPTK_Spatialize is enabled, the volume of the audio source depends on the distance between the audio source and the listener.
Beyong this distance, the volume is set to 0 and the midi player is paused. No effect if MPTK_Spatialize is disabled.

◆ MPTK_MidiEvents

List<TrackMidiEvent>? MidiPlayerTK.MidiFilePlayer.MPTK_MidiEvents
get

[DEPRECATED] Get all the raw midi events available in the midi file.
Use rather the method MPTK_ReadMidiEvents from the prefab class MidiFileLoader or from MidiFilePrefab (Pro only).

◆ MPTK_MidiIndex

int MidiPlayerTK.MidiFilePlayer.MPTK_MidiIndex
getset

Select a MIDI file to play by its Index.
The Index of a MIDI file is displayed in the popup from the MidiFilePlayer inspector and in the window "Midi File Setup" from the MPTK menu in the editor.

// Play the MIDI index 33
midiFilePlayer.MPTK_MidiIndex = 33;
midiFilePlayer.MPTK_Play();
Parameters
indexIndex of the MIDI, start from 0

◆ MPTK_MidiLoaded

MidiLoad MidiPlayerTK.MidiFilePlayer.MPTK_MidiLoaded
get

Get detailed information about the MIDI playing. This readonly properties is available only when a MIDI is playing.
Rather use the method MPTK_Load() to get information about a MIDI before playing. V2.82.

◆ MPTK_MidiName

virtual string MidiPlayerTK.MidiFilePlayer.MPTK_MidiName
getset

Select a MIDI to play with its name.
Use the exact name as seen in the MIDI setup windows (Unity menu MPTK/ without any path or extension.
Tips: Add MIDI files to your project with the Unity menu MPTK.

// Play the MIDI "Albinoni - Adagio"
midiFilePlayer.MPTK_MidiName = "Albinoni - Adagio";
midiFilePlayer.MPTK_Play();

◆ MPTK_PauseOnDistance

bool MidiPlayerTK.MidiSynth.MPTK_PauseOnDistance
getsetinherited

[obsolete] replaced by MPTK_Spatialize"); V2.83

◆ MPTK_PlayOnStart

bool MidiPlayerTK.MidiFilePlayer.MPTK_PlayOnStart
getset

Should the MIDI start playing when application starts ?

◆ MPTK_PlayTime

TimeSpan MidiPlayerTK.MidiFilePlayer.MPTK_PlayTime
get

Time from the start of playing the current midi

◆ MPTK_Position

double? MidiPlayerTK.MidiFilePlayer.MPTK_Position
getset

Set or get the current position in the MIDI when playing in milliseconds. Warning: if you want to set the start position, set MPTK_Position inside the processing of the event OnEventStartPlayMidi because MPTK_Play() reset the start position to 0. Other possibility to change the position in the MIDI is to use the property MPTK_TickCurrent: set or get the position in tick More info here https://paxstellar.fr/2020/09/11/midi-timing/

// Move forward one second
midiFilePlayer.MPTK_Position = midiFilePlayer.MPTK_Position + 1000d;

◆ MPTK_PositionFirstNote

double? MidiPlayerTK.MidiFilePlayer.MPTK_PositionFirstNote
get

Real time position in millisecond for the first note-on found.
Most MIDI don't start playing a note immediately. There is often a delay.
Use this attribute to known the real time wich it will start.
See also MPTK_TickFirstNote

◆ MPTK_PositionLastNote

double? MidiPlayerTK.MidiFilePlayer.MPTK_PositionLastNote
get

Real time position in millisecond for the last note-on found in the MIDI.
There is often other MIDI events after the last note-on: for example event track-end.
Use this attribute to known the real time when all sound will be stop.
See also the MPTK_DurationMS which provides the full time of all MIDI events including track-end, control at the beginning and at the end, ....
See also MPTK_TickLastNote

◆ MPTK_ProgramName

string? MidiPlayerTK.MidiFilePlayer.MPTK_ProgramName
get

Get Program track name if defined in the MIDI file with MIDI MetaEventType = ProgramName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html

◆ MPTK_PulseLenght

double MidiPlayerTK.MidiFilePlayer.MPTK_PulseLenght
get

Lenght in millisecond of a quarter. Obviously depends on the current tempo.

◆ MPTK_Quantization

int MidiPlayerTK.MidiFilePlayer.MPTK_Quantization
getset

Level of quantization :

  • 0 = None
  • 1 = Quarter Note
  • 2 = Eighth Note
  • 3 = 16th Note
  • 4 = 32th Note
  • 5 = 64th Note
  • 6 = 128th Note

◆ MPTK_RealTime

double MidiPlayerTK.MidiFilePlayer.MPTK_RealTime
get

V2.89.0 - Real time in milliseconds from the beginning of playing of the MIDI.
MIDI Tempo or Speed change have no impact, it's just a system timer not linked to MIDI information.

◆ MPTK_ReverbDecayHFRatio

float MidiPlayerTK.MidiSynth.MPTK_ReverbDecayHFRatio
getsetinherited

[MPTK PRO] - Decay HF Ratio : High-frequency to low-frequency decay time ratio.
Ranges from 0.1 to 2.0.

◆ MPTK_ReverbDecayTime

float MidiPlayerTK.MidiSynth.MPTK_ReverbDecayTime
getsetinherited

[MPTK PRO] - Reverberation decay time at low-frequencies in seconds.
Ranges from 0.1 to 20. Default is 1.

◆ MPTK_ReverbDelay

float MidiPlayerTK.MidiSynth.MPTK_ReverbDelay
getsetinherited

[MPTK PRO] - Late reverberation delay time relative to first reflection in seconds.
Ranges from 0 to 0.1. Default is 0.04

◆ MPTK_ReverbDensity

float MidiPlayerTK.MidiSynth.MPTK_ReverbDensity
getsetinherited

[MPTK PRO] - Reverberation density (modal density) in percent.
Ranges from 0 to 1.

◆ MPTK_ReverbDiffusion

float MidiPlayerTK.MidiSynth.MPTK_ReverbDiffusion
getsetinherited

[MPTK PRO] - Reverberation diffusion (echo density) in percent.
Ranges from 0 to 1. Default is 1.

◆ MPTK_ReverbDryLevel

float MidiPlayerTK.MidiSynth.MPTK_ReverbDryLevel
getsetinherited

[MPTK PRO] - Mix level of dry signal in output.
Ranges from 0 to 1.

◆ MPTK_ReverbHFReference

float MidiPlayerTK.MidiSynth.MPTK_ReverbHFReference
getsetinherited

[MPTK PRO] - Reference high frequency in Hz.
Ranges from 1000 to 20000. Default is 5000

◆ MPTK_ReverbLevel

float MidiPlayerTK.MidiSynth.MPTK_ReverbLevel
getsetinherited

[MPTK PRO] - Late reverberation level relative to room effect.
Ranges from 0 to 1.

◆ MPTK_ReverbLFReference

float MidiPlayerTK.MidiSynth.MPTK_ReverbLFReference
getsetinherited

[MPTK PRO] - Reference low-frequency in Hz.
Ranges from 20 to 1000. Default is 250

◆ MPTK_ReverbReflectionDelay

float MidiPlayerTK.MidiSynth.MPTK_ReverbReflectionDelay
getsetinherited

[MPTK PRO] - Late reverberation level relative to room effect.
Ranges from -10000.0 to 2000.0. Default is 0.0.

◆ MPTK_ReverbReflectionLevel

float MidiPlayerTK.MidiSynth.MPTK_ReverbReflectionLevel
getsetinherited

[MPTK PRO] - Early reflections level relative to room effect.
Ranges from 0 to 1.

◆ MPTK_ReverbRoom

float MidiPlayerTK.MidiSynth.MPTK_ReverbRoom
getsetinherited

[MPTK PRO] - Room effect level at low frequencies.
Ranges from 0 to 1.

◆ MPTK_ReverbRoomHF

float MidiPlayerTK.MidiSynth.MPTK_ReverbRoomHF
getsetinherited

[MPTK PRO] - Room effect high-frequency level.
Ranges from 0 to 1.

◆ MPTK_ReverbRoomLF

float MidiPlayerTK.MidiSynth.MPTK_ReverbRoomLF
getsetinherited

[MPTK PRO] - Room effect low-frequency level.
Ranges from 0 to 1.

◆ MPTK_SequenceTrackName

string? MidiPlayerTK.MidiFilePlayer.MPTK_SequenceTrackName
get

Get sequence track name if defined in the MIDI file with MIDI MetaEventType = SequenceTrackName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html

◆ MPTK_SFChorusDepth

float MidiPlayerTK.MidiSynth.MPTK_SFChorusDepth
getsetinherited

[MPTK PRO] - Set the SoundFont chorus effect depth
Chorus depth [0, 256]
V2.88.2

◆ MPTK_SFChorusLevel

float MidiPlayerTK.MidiSynth.MPTK_SFChorusLevel
getsetinherited

[MPTK PRO] - Set the SoundFont chorus effect level [0, 10]
V2.88.2 - becomes a parameter and default value set to 0.9 (was 2f, thank John)

◆ MPTK_SFChorusSpeed

float MidiPlayerTK.MidiSynth.MPTK_SFChorusSpeed
getsetinherited

[MPTK PRO] - Set the SoundFont chorus effect speed
Chorus speed in Hz [0.1, 5]
V2.88.2

◆ MPTK_SFChorusWidth

float MidiPlayerTK.MidiSynth.MPTK_SFChorusWidth
getsetinherited

[MPTK PRO] - Set the SoundFont chorus effect width
The chorus unit process a monophonic input signal and produces stereo output controlled by WIDTH macro.
Width allows to get a gradually stereo effect from minimum (monophonic) to maximum stereo effect. [0, 10]
V2.88.2

◆ MPTK_SFFilterQModOffset

float MidiPlayerTK.MidiSynth.MPTK_SFFilterQModOffset
getsetinherited

[MPTK PRO] - Quality Factor is defined in the SoundFont for each notes.
This parameter increase or decrease the default SoundFont value. Range: -96 to 96.

◆ MPTK_SFReverbDamp

float MidiPlayerTK.MidiSynth.MPTK_SFReverbDamp
getsetinherited

[MPTK PRO] - Set the SoundFont reverb effect damp [0,1].
Controls the reverb time frequency dependency. This controls the reverb time for the frequency sample rate/2
When 0, the reverb time for high frequencies is the same as for DC frequency.
When > 0, high frequencies have less reverb time than lower frequencies.
V2.88.2

◆ MPTK_SFReverbLevel

float MidiPlayerTK.MidiSynth.MPTK_SFReverbLevel
getsetinherited

[MPTK PRO] - Set the SoundFont reverb effect level
V2.88.2

◆ MPTK_SFReverbRoomSize

float MidiPlayerTK.MidiSynth.MPTK_SFReverbRoomSize
getsetinherited

[MPTK PRO] - Set the SoundFont reverb effect room size. Controls concave reverb time between 0 (0.7 s) and 1 (12.5 s)
V2.88.2

◆ MPTK_SFReverbWidth

float MidiPlayerTK.MidiSynth.MPTK_SFReverbWidth
getsetinherited

[MPTK PRO] - Set the SoundFont reverb effect width [0,100].
Controls the left/right output separation.
When 0, there are no separation and the signal on left and right output is the same.This sounds like a monophonic signal.
When 100, the separation between left and right is maximum.
V2.88.2

◆ MPTK_Spatialize

bool MidiPlayerTK.MidiSynth.MPTK_Spatialize
getsetinherited

Should the Spatialization effect must be enabled?
See here how to setup spatialization with Unity https://paxstellar.fr/midi-file-player-detailed-view-2/#Foldout-Spatialization-Parameters

◆ MPTK_SpatialSynthIndex

int MidiPlayerTK.MidiSynth.MPTK_SpatialSynthIndex
getinherited

Index of the MidiSynth for the dedicated Channel or Track when the prefab MidiSpatializer is used.
The MidiSynth reader (from a midi file) has no channel because no voice is played, so DedicatedChannel is set to -1

◆ MPTK_Speed

float MidiPlayerTK.MidiFilePlayer.MPTK_Speed
getset

Percentage value of the playing speed. Range 0.1 (10%) to 10 (1000%). Default is 1 for normal speed.

◆ MPTK_SynthRate

int MidiPlayerTK.MidiSynth.MPTK_SynthRate
getsetinherited

Get the the current synth rate or set free value (only if MPTK_EnableFreeSynthRate is true).

◆ MPTK_Tempo

double MidiPlayerTK.MidiFilePlayer.MPTK_Tempo
get

Get the current tempo from the MIDI file (independent from MPTK_Speed). Return QuarterPerMinuteValue similar to BPM (Beat Per Measure)

◆ MPTK_TextEvent

string? MidiPlayerTK.MidiFilePlayer.MPTK_TextEvent
get

Get Text if defined in the MIDI file with MIDI MetaEventType = TextEvent
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html

◆ MPTK_TickCurrent

long? MidiPlayerTK.MidiFilePlayer.MPTK_TickCurrent
getset

Set or get the current tick position in the MIDI when playing.
MIDI tick is an easy way to identify a position in a song independently of the time which could vary with tempo change.
The count of ticks for a quarter is constant all along a Midi: see properties MPTK_DeltaTicksPerQuarterNote.
Example: with a time signature of 4/4 the ticks length of a bar is 4 * MPTK_DeltaTicksPerQuarterNote.
Warning: if you want to set the start position, set MPTK_TickCurrent inside the processing of the event OnEventStartPlayMidi
because MPTK_Play() reset the start position to 0.
Other possibility to change the position in the MIDI is to use the property MPTK_Position: set or get the position in milliseconds
but tempo change event will impact also this time.
More info here https://paxstellar.fr/2020/09/11/midi-timing/

// Move forward one quarter
midiFilePlayer.MPTK_TickCurrent = midiFilePlayer.MPTK_TickCurrent + midiFilePlayer.MPTK_DeltaTicksPerQuarterNote;

◆ MPTK_TickFirstNote

long? MidiPlayerTK.MidiFilePlayer.MPTK_TickFirstNote
get

Tick position for the first note-on found.
Most MIDI don't start playing a note immediately. There is often a delay.
Use this attribute to known the tick position where the will start to play a sound.
See also MPTK_PositionFirstNote

◆ MPTK_TickLast

long? MidiPlayerTK.MidiFilePlayer.MPTK_TickLast
get

Last tick position in Midi: Value of the tick for the last MIDI event in sequence expressed in number of "ticks". MPTK_TickLast / MPTK_DeltaTicksPerQuarterNote equal the duration time of a quarter-note regardless the defined tempo.

◆ MPTK_TickLastNote

long? MidiPlayerTK.MidiFilePlayer.MPTK_TickLastNote
get

Tick position for the last note-on found.
There is often other MIDI events after the last note-on: for example event track-end.
Use this attribute to known the tick position time when all sound will be stop.
See also the MPTK_PositionLastNote which provides the last tich of the MIDI.

◆ MPTK_TrackCount

int? MidiPlayerTK.MidiFilePlayer.MPTK_TrackCount
get

Count of track read in the MIDI file

◆ MPTK_TrackInstrumentName

string? MidiPlayerTK.MidiFilePlayer.MPTK_TrackInstrumentName
get

Get Instrument track name if defined in the MIDI file with MIDI MetaEventType = TrackInstrumentName
See detail here https://ccrma.stanford.edu/~craig/14q/midifile/MidiFileFormat.html

◆ MPTK_TransExcludedChannel

int MidiPlayerTK.MidiSynth.MPTK_TransExcludedChannel
getsetinherited

Transpose will apply to all channels except this one. Set to -1 to apply to all channel. V2.89.0
Default is 9 because generally we don't want to transpose drum channel.

◆ MPTK_Transpose

int MidiPlayerTK.MidiSynth.MPTK_Transpose
getsetinherited

Transpose note from -24 to 24

◆ MPTK_Volume

float MidiPlayerTK.MidiSynth.MPTK_Volume
getsetinherited

Global Volume. apply to all channels.
Must be >=0 and <= 1

Event Documentation

◆ OnAudioFrameStart

OnAudioFrameStartHandler MidiPlayerTK.MidiSynth.OnAudioFrameStart
inherited

[MPTK PRO] - this event is triggered at each start of a new audio frame from the audio engine.
The parameter (double) is the current synth time in milliseconds. See example of use.
The callbach function will not run on the Unity thread, so you can't call Unity API except Debug.Log.

// 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, init the last time
lastSynthTime = synthTimeMS;
// Calculate time in millisecond since the last loop
double deltaTime = synthTimeMS - lastSynthTime;
lastSynthTime = synthTimeMS;
timeMidiFromStartPlay += deltaTime;
// Calculate time since last beat played
timeSinceLastBeat += deltaTime;
// Slider SldTempo in BPM.
// 60 BPM means 60 beats in each minute, 1 beat per second, 1000 ms between beat.
// 120 BPM would be twice as fast: 120 beats in each minute, 2 per second, 500 ms between beat.
// Calculate the delay between two quarter notes in millisecond
CurrentTempo = (60d / SldTempo.Value) * 1000d;
// Is it time to play a hit ?
if (IsPlaying && timeSinceLastBeat > CurrentTempo)
{
timeSinceLastBeat = 0d;
CurrentBeat++;
}
}