MusIT

API MPTK – Playing MIDI by script

Introduction

One of the strengths of MPTK is the ability for playing music with any line of script. But, for more complex needs, you will have to write some Unity scripts.

Above all, don’t be worried, MPTK API is quite simple and well documented. On the other hand, writing script with Unity requires two skills:

  • Understanding Unity scripting principles
  • Learn C# language. Basic knowledge may be sufficient at the start.

Don’t Panic!

There are Excellent Guides to this Galaxy!

Training & Doc

Unity proposes a lot of well done tutorials, to begin, I encourage you to follow these two tutorials:

  • Start with Beginner Scripting to learn about programming for game development, from the very beginning with easy to follow video tutorials.
  • You need also to learn how writing script with the language C#. There is no need to become a master. Thanks to C# which is quite simple. Associated with Unity, a C# beginner can build great thing. Take the time to follow this tuto Coding in C# in Unity for beginners .

On top of that, Maestro MPTK contains an API which is a set of class, functions and attributes.

Look here to see the full API documentation.

What you be able to do

By script, you have access to all the MPTK features, much more than from the inspector. See bellow, a quick overview.

Maestro MPTK Free

  • Playing MIDI Music from MIDI file, see MidiFilePlayer prefab and class
  • Playing Generated Music from your algorithm, see MidiStreamPlayer prefab and class and MPTKEvent class.
  • Loading a MIDI file and get access to all the MIDI events, see MidiFileLoader prefab and class.

Maestro MPTK Pro

  • Playing External MIDI, see MidiExternalPlayer prefab and class.
  • Writing a MIDI file, see MPTKWriter class.
  • Defined play list with overlap and play extract of MIDI, see MidiListPlayer prefab and class.
  • Reading MIDI events from a MIDI keyboard, see MidiInReader prefab and class.
  • Spatialize each instruments from a a MIDI file, see MidiSpatializer prefab and class.
  • Changing on fly the current SoundFont or bank, see API in MidiPlayerGlobal class.
  • Applying effects as filter, reverb, chorus.
  • Build Scales and Chords.
  • Music looping.
  • Programmatically SoundFont loading.

Quick Guide

First step, create your scene

Classically, the Unity scene contains all the necessary gameObjects for your project. In addition, don’t forget to save your scene outside MidiPlayer folder in order to easily update MPTK when new versions are available.

Except for some classes as MidiPlayerGlobal or MPTKWriter, you can’t use directly the MPTK classes because these classes need others components to work correctly.

Rather, add MPTK prefab in your scene hierarchy, directly at the top level of your scene hierarchy or attached to another gameObject (2D or 3D Object, Camera, Light … ).

There is surely a prefab for your need! All you have to do is to add this prefab to your scene. Drag and drop from Unity Project Tab:

Example with the prefab MidiFilePlayer

Choose your MPTK prefab depending of your need:

Maestro prefab list

Prefab available with Maestro MPTK Free

  • MidiFilePlayer: play music from a MIDI file.
  • MidiStreamPlayer: create music from algo.
  • MidiFileLoader: load a MIDI file for analysis or processing purpose.

Prefab available with Maestro MPTK Pro

  • MidiListPlayer: play music from list of MIDI files, overlap between MIDI, play part of a MIDI, loop …
  • MidiExternalPlay: playing a MIDI directly from the Web or anywhere on the desktop.
  • MidiInReader: read MIDI events from a MIDI keyboard, play directly, or do anything that you want with the MIDI events.
  • MidiSpatializer: play music from a MIDI files with the spatializer ready for a 3D environnement.

Second step, create your script

  • Add a GameObject or reuse an existing one in your scene hierarchy.
  • Add a new script to your GameObject:
Add a new script
  • Edit your script with your preferred editor:
Edit the script
  • You’ll need to add the following at the top of any C# script that need to use MPTK API:
    using MidiPlayerTK
  • For using the MPTK methods or attributes, your script must retrieve a reference to your prefab added in your scene.
  • So, declare a variable in your script depending the type of prefab you are using, one of them or all!
C#
public MidiFilePlayer midiFilePlayer;
public MidiStreamPlayer midiStreamPlayer;
public MidiFileLoader MidiLoader;
public MidiExternalPlayer midiExternalPlayer;
public MidiInReader midiInReader;
public MidiListPlayer midiListPlayer;

Third step, associate the prefab

Linking the prefab to the variable defined in your script is essential; otherwise, you may encounter an error such as “NullReferenceException: Object reference not set to an instance of an object.” There are two methods that can work together.

First method, with Unity Editor

In the inspector of the GameObject that has your script, drag and drop a MidiFilePlayer prefab into the “Midi File Player” field.

Drag and drop a prefab into the script variable
Unity highlight the prefab selected in the scene

Warning: Always associate a prefab from your scene hierarchy, never from the Unity project tab! That will not work!

Second method, by script

In your script, write something like that, preferably in the Start() method:

C#
using MidiPlayerTK;

public class MySimplePlayer : MonoBehaviour
{
   public MidiFilePlayer midiFilePlayer ;

   // Use this for initialization
   void Start()
   {
      midiFilePlayer = FindObjectOfType<MidiFilePlayer>();
   }
}

Bravo! You can now utilize the MPTK API and discover its vast potential! Check here for the complete API documentation.

Some important tips

  • All methods and properties are prefixed with MPTK_. Please, don’t use the others! They can be modified or removed without prior notice.
  • Also, avoid using methods or attributes not documented, they could change without prior notifice.
  • Some methods are virtual : also it’s better to encapsulate MPTK class with your own class than modifying MPTK source code if you want to keep the benefit of the future releases.
  • Don’t miss also this post which explains how using Maestro MPTK without adding prefab to the scene. Useful to create many MidiFilePlayer programmatically!

Examples

Example of MPTK API with MidiFilePlayer Class

C#
midiFilePlayer.MPTK_MidiName = "Albinoni - Adagio";
midiFilePlayer.MPTK_Play();

// Change speed of playing. Adagio transformed to Allegretto ;-)
midiFilePlayer.MPTK_Speed = 2f; 

// Change instrument because you don't like the strings
midiFilePlayer.MPTK_ChannelForcedPresetSet(0, 10);

// Disable drum. Albinoni Adagio without drum ? strange ...
midiFilePlayer.MPTK_ChannelEnableSet(9, false);

Example of MPTK API with MidiStreamPlayer Class

Just play a note!

C#
// Example of MPTK API with MidiStreamPlayer Class
private void PlayOneNote()
{
 // Play a note C5 for 1 second on the channel 0
 NotePlaying = new MPTKEvent()
 {
    Command = MPTKCommand.NoteOn,
    Value = 60,  //C5
    Channel = 0,
    Duration = 1000f,
    Velocity = 100,
    Delay = 0f,
  };
  midiStreamPlayer.MPTK_PlayEvent(NotePlaying);
}

Just play a chord! (Pro version)

C#
// Play a C5 Maj chord (MPTK Pro)
ChordLibPlaying = new MPTKChordBuilder(true)
{
   // Parameters to build the chord
   Tonic = 60,
   FromLib = 0,
   Channel = 0,
   Arpeggio = 50, // delay in milliseconds between each notes of the chord
   Duration = 1000f,
   Velocity = 100f
   Delay = 0,
}
midiStreamPlayer.MPTK_PlayChordFromLib(ChordLibPlaying);

Some examples in the package could be useful for you

  • CatchMusic – MIDI music with preprocessing before playing. In short, could become a complete game in the future or for you if you have the desire đŸ˜‰
  • EuclideanRhythm – how to build a rythmic box! (Pro only)
  • TestMidiFilePlayerWithScript – play MIDI music with a GUI, change SoundFont (Pro version)
  • TestMidiStreamSimple – very simple example for generating music. It’s useful for my regression tests but also for you to quickly understand the two methods available to generate music.

Full example code with MidiExternalPlayer prefab (Pro version)

C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using MidiPlayerTK;

public class SimplePlayer : MonoBehaviour
{
    /// <summary>
    /// MPTK component able to play a Midi file from an external source. 
    /// Add a PreFab MidiExternalPlayer your scene.
    /// </summary>
    public MidiExternalPlayer midiExternalPlayer;

    private void Start()
    {
        // Find the Midi external component 
        if (midiExternalPlayer == null)
        {
            // Not found, try to find in the scene.
            Debug.Log("No midiExternalPlayer defined with the editor inspector, try to find one");
            MidiExternalPlayer fp = FindObjectOfType<MidiExternalPlayer>();
            if (fp == null)
                Debug.Log("Can't find a MidiExternalPlayer in the scene. No music will be played");
            else
            {
                midiExternalPlayer = fp;
            }
        }

        if (midiExternalPlayer != null)
        {
            // Event trigger for each group of notes read from midi file
            if (!midiExternalPlayer.OnEventNotesMidi.HasEvent())
            {
                // Set event by script
                Debug.Log("OnEventNotesMidi defined by script");
                midiExternalPlayer.OnEventNotesMidi.AddListener(ReadNotes);
            }
            else
                Debug.Log("OnEventNotesMidi defined by Hierarchy in Unity editor");
        }
    }

    /// <summary>
    /// Event fired by MidiFilePlayer when Midi notes are available
    /// from the MPTK sequencer.
    /// Try this in the inputfield: http://www.midiworld.com/midis/other/c2/bolero.mid   
    /// </summary>
    public void ReadNotes(List<MPTKEvent> notes)
    {
        Debug.Log("Notes count: " + notes.Count);
        foreach (MidiPlayerTK.MPTKEvent midiEvent in notes)
            if (midiEvent.Command == MPTKCommand.NoteOn)
                Debug.Log(" Channel:" + midiEvent.Channel +
                          " Note:" + midiEvent.Value + 
                          " Velocity:" + midiEvent.Velocity + 
                          " Duration:" + midiEvent.Duration + " ms");
    }


    /// <summary>
    /// Other method: play is fired from the a button or an input field
    /// The URL is used to load the midi file from a web site.
    /// </summary>
    /// <param name="uri">uri or path to the midi file</param>
    public void Play(string uri)
    {
        Debug.Log("Play from script:" + uri);
        midiExternalPlayer.MPTK_Stop();
        midiExternalPlayer.MPTK_MidiName = uri;
        midiExternalPlayer.MPTK_Play();
    }
}

Have Fun!

  1. Hello John Sorry for the delay to answer. I’m not well follow comments on my blog, rather use my discord…

  2. Thanks Tierry, to clarify im not trying to get an external device to integrate, I have a piano prefab that…

  3. Hello John, Thank for your interest with Maestro MPTK! Integration with an external MIDI device is possible with MPTK Pro.…

Get MPTK from the Unity store

If you like Midi Player Tool Kit, please leave a review on the Asset Store. It’s very appreciated!!!

Maestro MPTK on ChatGPT!

From various MPTK documentation sources, @DarkSky42 has created a custom LLM based on ChatGPT. You can now ask all the questions you want and get a good level of answer: request code example, verify your source code, explain the MPTK demo …

Contact

If you have questions, please don’t hesitate to contact us via the dedicated Unity forum or our Discord  channel.

Reach the Discord archive by topic.

We are always happy to discuss your projects!

Add MIDI Music With 3 Clicks for Free

Sound Spatialisation, MPTK is ready for Virtual Reality [Pro]

Sound Spatialisation, MPTK is ready for Virtual Reality [free]

Midi Synth : Real Time Voice Effect Change

Euclidean Rhythm demo

The Deezer playlist that helped me create Maestro