Prefab MidiStreamPlayer V2

MidiStreamPlayer is a Prefab that you can use to play a Midi  music without Midi file: you generate Midi event from your code and send it to MidiStreamPlayer.

See an example with source code at the end of this page.

Inspector parameters

  • Volume set the default volume of the playing.
  • Pause with distance if checked, automatically pause the play if distance between the gameobject MidiFilePlayer and the AudioListener is greater than MaxDistance.
  • MaxDistance distance for the pause with distance function.
  • Transpose transpose the music by half tone.

Others Foldout

Integration of MidiStreamPlayer in your script

See TestMidiStreamScripting.cs for the whole example.

using MidiPlayerTK;
...
// MPTK component able to play a stream of midi events
public MidiStreamPlayer midiStreamPlayer;
...
if (midiStreamPlayer != null)
{
   if (!midiStreamPlayer.OnEventSynthStarted.HasEvent())
       midiStreamPlayer.OnEventSynthStarted.AddListener(EndLoadingSynth);
}
else
   Debug.LogWarning("No Stream Midi Player associed to this game object");

public void EndLoadingSynth(string name)
{
   midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent() { Command = MPTKCommand.PatchChange, Value = CurrentPatchInstrument, Channel = StreamChannel, });
}

private void BankPatchChanged(object tag, int index)
{
   switch ((string)tag)
   {
      case "BANK_INST":
           midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
           { 
               Command = MPTKCommand.ControlChange, 
               Controller = MPTKController.BankSelect, 
               Value = index, 
               Channel = StreamChannel,
           });
           break;

      case "PATCH_INST":
           midiStreamPlayer.MPTK_PlayEvent(new MPTKEvent()
           { 
               Command = MPTKCommand.PatchChange, 
               Value = index, 
               Channel = StreamChannel, 
           });
           break;
}

void Update()
{
   ...    
    // Start playint a new note
    NotePlaying = new MPTKEvent()
    {
       Command = MPTKCommand.NoteOn,
       Value = CurrentNote,
       Channel = StreamChannel,
       Duration = 9999999, // 9999 seconds but stop by the new note. See before.
       Velocity = Velocity // Sound can vary depending on the velocity
     };
     midiStreamPlayer.MPTK_PlayEvent(NotePlaying);

   ...    

     if (NotePlaying != null)
     {
        // Stop the note (method to simulate a real human on a keyboard : duration is not known when note is triggered)
        midiStreamPlayer.MPTK_StopEvent(NotePlaying);
        NotePlaying = null;
     }
}