Connecting MIDI devices to Bela!
Connect a USB MIDI device to Bela and try out our MIDI API. This example by default opens the MIDI port "hw:1,0,0"
, which normally corresponds to the first USB device that is plugged in. You can run amidi -l
on the terminal to check which devices are available and edit this file accordingly. The device "hw:0,0,0"
is (on Bela images v0.3 and above) a virtual MIDI device to the host computer over the USB port.
Every time a MIDI message comes in, the midiMessageCallback()
function is called. In this example, we detect NoteOn messages and we use them to generate a sinewave with given frequency and amplitude. We can also write MIDI messages, by sending a sequence of bytes with writeOutput()
.
#include <libraries/Midi/Midi.h>
#include <stdlib.h>
#include <cmath>
float gFreq;
float gPhaseIncrement = 0;
bool gIsNoteOn = 0;
int gVelocity = 0;
float gSamplingPeriod = 0;
int gSampleCount = 44100;
if(arg != NULL){
rt_printf("Message from midi port %s ", (const char*) arg);
}
if(message.
getType() == kmmNoteOn){
gFreq = powf(2, (message.
getDataByte(0) - 69) / 12.f) * 440.f;
gVelocity = message.getDataByte(1);
gPhaseIncrement = 2.f * (float)M_PI * gFreq * gSamplingPeriod;
gIsNoteOn = gVelocity > 0;
rt_printf("v0:%f, ph: %6.5f, gVelocity: %d\n", gFreq, gPhaseIncrement, gVelocity);
}
}
void sysexCallback(midi_byte_t byte, void* arg)
{
printf("Sysex byte");
if(arg != NULL){
printf(" from midi port %s", (const char*) arg);
}
printf(": %d\n", byte);
}
const char* gMidiPort0 = "hw:1,0,0";
{
return true;
}
enum {kVelocity, kNoteOn, kNoteNumber};
{
for(
unsigned int n = 0; n < context->
audioFrames; n++){
float value;
if(gIsNoteOn == 1){
static float phase = 0;
phase += gPhaseIncrement;
if(phase > M_PI)
phase -= 2.f * (float)M_PI;
value = sinf(phase) * gVelocity/128.0f;
} else {
value = 0;
}
static int count = 0;
if(count % gSampleCount == 0){
static bool state = 0;
state = !state;
midi_byte_t statusByte = 0xB0;
midi_byte_t controller = 30;
midi_byte_t value = state * 127;
midi_byte_t bytes[3] = {statusByte, controller, value};
}
++count;
}
}
{
}