Set Synthesizer Parameters at Startup

Use case: you want to generate music with an instrument (preset, patch, program, there is a lot of synonyms!) other than Piano at the startup of your application.

By default when the synthesizer is loaded, all channels are set with the preset 0. Generally, preset 0 is associated with Piano moreover when it’s a General Midi SoundFont.

The method MPTK_ChannelPresetChange must be used for changing preset with a prefab MidiPlayerStream.

But, the method must be called just after the synthesizer is initialized. So, we used the event OnEventSynthStarted to call EndLoadingSynth (or the name that you want!) in the script.

This process can be applied for a lot of synthesizer parameters, for example Kill By Exclusive Class , or Release Same Note (If the same note is hit twice on the same channel, then the older voice process is advanced to the release stage).

Try this code in your script:

void Start() { if (midiStreamPlayer != null) { // The call of this methods can also be defined // in the prefab MidiStreamPlayer from the Unity // editor inspector. See "On Event Synth Started. // Below by script: EndLoadingSynth is defined to be called when the synthesizer is ready. if (!midiStreamPlayer.OnEventSynthStarted.HasEvent()) midiStreamPlayer.OnEventSynthStarted.AddListener(EndLoadingSynth); } else // Your public variable midiStreamPlayer must be defined with the inspector Unity editor. // Or by script, use the method FindObjectOfType Debug.LogWarning("midiStreamPlayer is not defined. Check in Unity editor inspector of this gameComponent"); } /// <summary> /// This methods is run when the synthesizer is ready. /// It's a good place to set some synth parameter's as defined preset by channel /// </summary> /// <param name="name"></param> public void EndLoadingSynth(string name) { Debug.LogFormat($"Synth {name} is loaded"); // Set music box (preset 10) to channel 0. // Could be different for another SoundFont. midiStreamPlayer.MPTK_ChannelPresetChange(0, 10); Debug.LogFormat($"Preset {midiStreamPlayer.MPTK_ChannelPresetGetName(0)} defined on channel 0"); // Set reed organ (preset 20) to channel 1. Could be different for another SoundFont. midiStreamPlayer.MPTK_ChannelPresetChange(1, 20); Debug.LogFormat($"Preset {midiStreamPlayer.MPTK_ChannelPresetGetName(1)} defined on channel 1"); // Disable kill sound with same exclusive class midiStreamPlayer.MPTK_KillByExclusiveClass = false; }

Tip: don’t forget to defined the variable midiStreamPlayer! See here for more details.

Was this helpful?

0 / 0