Skip to content

Instantly share code, notes, and snippets.

@maddievision
Created September 6, 2013 21:22
Show Gist options
  • Save maddievision/6470181 to your computer and use it in GitHub Desktop.
Save maddievision/6470181 to your computer and use it in GitHub Desktop.
MIDI Input Logger (OS X)
//Andrew Lim 2013-09-07
//Compile with: -framework CoreMIDI -framework CoreFoundation -framework CoreAudio
#include <stdio.h>
#include <CoreMIDI/CoreMIDI.h>
const char * const NOTE_NAMES[] = {
"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"
};
int getNoteName(char* output, int notenumber) {
return sprintf(output, "%s%d", NOTE_NAMES[notenumber % 12], notenumber / 12);
}
void midiProcessor (
const MIDIPacketList *pktlist,
void *readProcRefCon,
void *srcConnRefCon )
{
const MIDIPacket *packet = &pktlist->packet[0];
printf ("Received Packets: (%d)\n",pktlist->numPackets);
for (int i = 0; i < pktlist->numPackets; ++i) {
Byte status = packet->data[0];
Byte stat = status >> 4;
Byte chan = status & 0xF;
switch (stat) {
case 0x8: {
Byte note = packet->data[1];
Byte velocity = packet->data[2];
char notename[64];
getNoteName(notename,note);
printf("Note Off %s (%d)\n",notename,velocity);
} break;
case 0x9: {
Byte note = packet->data[1];
Byte velocity = packet->data[2];
char notename[64];
getNoteName(notename,note);
printf("Note On %s (%d)\n",notename,velocity);
} break;
case 0xA: {
Byte note = packet->data[1];
Byte pressure = packet->data[2];
char notename[64];
getNoteName(notename,note);
printf("Note Pressure %s (%d)\n",notename,pressure);
} break;
case 0xB: {
Byte cc = packet->data[1];
Byte value = packet->data[2];
printf("Control Change #%d (%d)\n",cc,value);
} break;
case 0xC: {
Byte program = packet->data[1];
printf("Program Change (%d)\n",program);
} break;
case 0xD: {
Byte pressure = packet->data[1];
printf("Channel Pressure (%d)\n",pressure);
} break;
case 0xE: {
Byte pitchLSB = packet->data[1];
Byte pitchMSB = packet->data[2];
int pitch = ((int)pitchLSB) + ((((int)pitchMSB) << 7)) - 0x2000;
printf("Pitch Bend (%d)\n",pitch);
} break;
default: {
}
}
packet = MIDIPacketNext (packet);
}
}
int main(int argc, char ** argv) {
ItemCount srcCount = MIDIGetNumberOfSources();
for (int i = 0; i < srcCount; i++) {
MIDIEndpointRef source = MIDIGetSource(i);
CFStringRef x;
OSStatus err = MIDIObjectGetStringProperty(source,kMIDIPropertyName,&x);
const char* srcName = CFStringGetCStringPtr(x, kCFStringEncodingMacRoman);
printf("%d: %s\n",i,srcName);
}
int selSource = 0;
OSStatus err;
MIDIClientRef client;
err = MIDIClientCreate(CFSTR("Test Player"),NULL,NULL,&client);
MIDIEndpointRef outp = MIDIGetSource(selSource);
MIDIPortRef op;
err = MIDIInputPortCreate(client,CFSTR("Test Port"),midiProcessor,NULL,&op);
err = MIDIPortConnectSource(op,outp,NULL);
printf("Connection established...\n");
while (1+1==2) {
// lol
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment