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:

// MPTK component able to play a stream of notes like midi notes generated public MidiStreamPlayer midiStreamPlayer; void Start() { // Find the prefab MidiStreamPlayer in the hierarchy. Can also be set in the inspector. midiStreamPlayer = FindObjectOfType<MidiStreamPlayer>(); if (midiStreamPlayer == null) Debug.LogWarning("Can't find a MidiStreamPlayer Prefab in the Hierarchy. No music will be played"); else // The call of this methods can also be defined in the editor inspector. // See "On Event Synth Started. // EndLoadingSynth will be called when the synthesizer is ready. midiStreamPlayer.OnEventSynthStarted.AddListener(EndLoadingSynth); } /// <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. 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; }
Code language: PHP (php)

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