Tutorial: Handling MIDI events

Table of Contents


This tutorial illustrates how to handle MIDI input events. In addition to handing MIDI data from an external source, an on-screen keyboard component is introduced.

Level: Intermediate

Platforms: Windows, macOS, Linux

Classes: AudioDeviceManager, MidiMessage, MidiInputCallback, ComboBox, MidiKeyboardComponent, MidiKeyboardState, CallbackMessage, ScopedValueSetter

Getting started

Download the demo project for this tutorial here: PIP | ZIP. Unzip the project and open the first header file in the Projucer.

If you need help with this step, see Tutorial: Projucer Part 1: Getting started with the Projucer.

Note
Ideally, you should have an external MIDI source attached to your computer. Failing this, some kind of virtual MIDI source (that create virtual MIDI ports on the computer) would be helpful.

The demo project

The demo project presents an on-screen MIDI keyboard and allows the user to select one of the hardware device MIDI inputs using a combo-box. MIDI events received from either of these sources are displayed in the lower part of the window. This is shown in the following screenshot:

tutorial_handling_midi_events_screenshot1.png
The application window

MIDI input

This tutorial demonstrates how to handle MIDI input in a basic application. JUCE makes it easy to discover the list of connected hardware MIDI interfaces. It also provides the MidiKeyboardComponent class that allows you to display an on-screen keyboard. First, let's look at the member variables in our MainContentComponent class:

AudioDeviceManager deviceManager; // [1]
ComboBox midiInputList; // [2]
Label midiInputListLabel;
int lastInputIndex = 0; // [3]
bool isAddingFromMidiInput = false; // [4]
MidiKeyboardState keyboardState; // [5]
MidiKeyboardComponent keyboardComponent; // [6]
TextEditor midiMessagesBox;
double startTime;

In the MainContentComponent constructor we initialise [3], [4], and [6]. We also take a note of the application start time so we can display the MIDI data timestamps relative to this.

MainContentComponent()
: keyboardComponent (keyboardState, MidiKeyboardComponent::horizontalKeyboard),
startTime (Time::getMillisecondCounterHiRes() * 0.001)
{
//...

We must pass a MidiKeyboardState object to initialise the MidiKeyboardComponent object. And, since these are statically allocated objects the MidiKeyboardState must be listed first in our member variables.

MIDI input list

The combo-box containing the list of MIDI inputs is populated by getting the list of MIDI inputs connected to the computer from the MidiInput class using the MidiInput::getDevices() function:

//...
addAndMakeVisible (midiInputList);
midiInputList.setTextWhenNoChoicesAvailable ("No MIDI Inputs Enabled");
auto midiInputs = MidiInput::getDevices();
midiInputList.addItemList (midiInputs, 1);
midiInputList.onChange = [this] { setMidiInput (midiInputList.getSelectedItemIndex()); };
// find the first enabled device and use that by default
for (auto midiInput : midiInputs)
{
if (deviceManager.isMidiInputEnabled (midiInput))
{
setMidiInput (midiInputs.indexOf (midiInput));
break;
}
}
// if no enabled devices were found just use the first one in the list
if (midiInputList.getSelectedId() == 0)
setMidiInput (0);
//...

If the user changes the selected MIDI input then the lambda function assigned to the ComboBox::onChange helper object will be called:

midiInputList.onChange = [this] { setMidiInput (midiInputList.getSelectedItemIndex()); };

The setMidiInput() function makes our application start listening to the selected device. It also enables the device if it is currently disabled:

void setMidiInput (int index)
{
auto list = MidiInput::getDevices();
deviceManager.removeMidiInputCallback (list[lastInputIndex], this);
auto newInput = list[index];
if (! deviceManager.isMidiInputEnabled (newInput))
deviceManager.setMidiInputEnabled (newInput, true);
deviceManager.addMidiInputCallback (newInput, this);
midiInputList.setSelectedId (index + 1, dontSendNotification);
lastInputIndex = index;
}

Handling external MIDI input

We implement the MidiInputCallback::handleIncomingMidiMessage() pure virtual function. This updates the keyboard state (which in turn will update the MidiKeyboardComponent object):

void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message) override
{
const ScopedValueSetter<bool> scopedInputFlag (isAddingFromMidiInput, true);
keyboardState.processNextMidiEvent (message);
postMessageToList (message, source->getName());
}

Notice the scopedInputFlag variable makes use of the ScopedValueSetter class. This does the following:

The MIDI keyboard state and component

In the MainContentComponent constructor the MidiKeyboardComponent object is added to our MainContentComponent parent component and made visible. We also listen to the MidiKeyboardState object (not the component):

//...
addAndMakeVisible (keyboardComponent);
keyboardState.addListener (this);
//...

The MidiKeyboardStateListener class has two pure virtual functions that we must implement. These are the MidiKeyboardStateListener::handleNoteOn() and MidiKeyboardStateListener::handleNoteOff() functions.

void handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override
{
if (! isAddingFromMidiInput)
{
auto m = MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity);
postMessageToList (m, "On-Screen Keyboard");
}
}
void handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber, /*float velocity*/) override
{
if (! isAddingFromMidiInput)
{
auto m = MidiMessage::noteOff (midiChannel, midiNoteNumber);
postMessageToList (m, "On-Screen Keyboard");
}
}

Here you can see how the isAddingFromMidiInput member is used. This prevents events that arrived from the hardware input from being posted to our list more than once.

Posting messages to the list

The postMessageToList() function may look a little unusual at first:

void postMessageToList (const MidiMessage& message, const String& source)
{
(new IncomingMessageCallback (this, message, source))->post();
}

The IncomingMessageCallback class is a subclass of the CallbackMessage class. We need to use this since we can't be sure from which thread the postMessageToList() function will be called. It will be called from the message thread if the user clicks on the MidiKeyboardComponent object. But, if the data arrives from an external MIDI source then it will be called from the background MIDI thread (possibly an operating system thread).

The CallbackMessage class provides a means of calling a function on the message thread. The CallbackMessage class is a kind of ReferenceCountedObject class. This is why we don't (apparently) need to store the IncomingMessageCallback object anywhere. In fact, the IncomingMessageCallback::post() function (which is the MessageManager::MessageBase::post() function) adds the object to a queue that is handled by the MessageManager class. The MessageManager class will eventually find this object in the queue and call the IncomingMessageCallback::messageCallback() function on the message thread. Once this function has been called, the IncomingMessageCallback object will be deleted. Thus the lifetime of this object is handled (almost) automatically.

Note
This is only really necessary since we need to send the data to the message thread. It is likely that some kind of inter-thread communication is necessary in a MIDI application but the exact implementation depends on the circumstances.

Displaying the messages

The addMessageToList() and getMidiMessageDescription() functions are very similar to these functions from Tutorial: Create MIDI data. The main difference is that we make a note of the source [7] of the MIDI message (which hardware input, or the on-screen keyboard):

void addMessageToList (const MidiMessage& message, const String& source)
{
auto time = message.getTimeStamp() - startTime;
auto hours = ((int) (time / 3600.0)) % 24;
auto minutes = ((int) (time / 60.0)) % 60;
auto seconds = ((int) time) % 60;
auto millis = ((int) (time * 1000.0)) % 1000;
auto timecode = String::formatted ("%02d:%02d:%02d.%03d",
hours,
minutes,
seconds,
millis);
auto description = getMidiMessageDescription (message);
String midiMessageString (timecode + " - " + description + " (" + source + ")"); // [7]
logMessage (midiMessageString);
}
Exercise
Add some sliders to the user interface that transmit and respond to messages such as modulation wheel (CC1) and pitch wheel.

Summary

This tutorial has introduced some classes for handing and displaying MIDI input events. In particular you should be able to:

See also