API MPTK – Integrate MPTK in your script

One of the strengths of MPTK is the ability for playing music with no 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 and learn C# language.

Don’t Panic!

There are Excellent Guides to this Galaxy!

Unity proposes a lot of excellent tutorials have a look here. Lock the door, shutdown your phone, make coffee or tee … and learn! it’s a journey with sometimes disappointment, nervousness, frustration but you will discover beautiful landscape. The main key of success is perseverance.

You need also to learn writing script in language C#. There is no need to becomes a master, C# is quite simple and associated to Unity, a C# beginner can build great thing. But, you need to take the time to follow this tuto Coding in C# in Unity for beginners The main key of success ? see previous paragraph.

On top of that, MPTK contains an API (a set of functions and attributes) which facilitate reaching your target.

With Free and Pro versions of MPTK you will be able to:

  • Playing Midi Music from midi file, see MidiFilePlayer prefab and class
  • Playing Generated Music from 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.

In addition with the Pro version, you can also:

  • Playing External Midi, see MidiExternalPlayer prefab and class.
  • Writing a Midi file, see MidiFileWriter 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.

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 MidiPlayerGlobal or MidiFileWriter, 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:

Prefab available for 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 Pro version

  • 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!

  • First of all, add your script to a gameObject (empty or not) in your scene hierarchy.
  • Edit your script with your preferred editor. You’ll need to add the following at the top of any C# script that need to use MPTK API: using MidiPlayerTK;
  • Some tips:
    • All methods and properties are prefixed with MPTK_. To clarify, don’t use the others ! They can be modified or removed without any information.
    • Also, avoid using methods or attributes not documented, they could change without any notification.
    • 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.

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:

public MidiFilePlayer midiFilePlayer; public MidiStreamPlayer midiStreamPlayer; public MidiFileLoader MidiLoader; public MidiExternalPlayer midiExternalPlayer; public MidiInReader midiInReader; public MidiListPlayer midiListPlayer;

Then, associate the prefab to the variable added in your script.

First method, with Unity Editor:

On the inspector of the gameObject which contains your script, drag and drop a prefab to the field “Midi File Player” (your variable midiFilePlayer has been set to uppercase by Unity with space inserted, I known that could be not intuitive!):

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:

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

Now you are able to use the MPTK API! Look at scripts from demo, for example : TestMidiFilePlayerScripting.cs

Example of MPTK API with MidiFilePlayer Class

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

// 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); }
// 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);

Download API documentation (PDF)

We hate huge documentation! Consequently methods and attributes inherited are not duplicated in each class.

Also, a Help file (.chm) is available with the asset.

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):

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!

No comments to show.