1 /* Modified code from http://tldp.org/HOWTO/MIDI-HOWTO-9.html
2 * This will print ALSA-Seq (MIDI) events to stdout for further processing eg.: in Arduino
8 #include <alsa/asoundlib.h>
10 #define MIDI_NOTE_OFF 128
11 #define MIDI_NOTE_ON 144
12 #define MIDI_CONTROL 176
13 #define MIDI_PITCH_BEND 224
14 #define MIDI_FORMAT "%c%c%c"
15 #define MIDI_FORMAT_ERR "%d:%d:%d\n"
17 snd_seq_t
*open_seq();
18 void midi_action(snd_seq_t
*seq_handle
);
20 snd_seq_t
*open_seq() {
22 snd_seq_t
*seq_handle
;
25 if (snd_seq_open(&seq_handle
, "hw", SND_SEQ_OPEN_DUPLEX
, 0) < 0) {
26 fprintf(stderr
, "Error opening ALSA sequencer.\n");
29 snd_seq_set_client_name(seq_handle
, "ALSA Sequencer Pipe");
30 if ((portid
= snd_seq_create_simple_port(seq_handle
, "ALSA Sequencer Pipe",
31 SND_SEQ_PORT_CAP_WRITE
|SND_SEQ_PORT_CAP_SUBS_WRITE
,
32 SND_SEQ_PORT_TYPE_APPLICATION
)) < 0) {
33 fprintf(stderr
, "Error creating sequencer port.\n");
39 void midi_action(snd_seq_t
*seq_handle
) {
44 snd_seq_event_input(seq_handle
, &ev
);
46 case SND_SEQ_EVENT_CONTROLLER
:
47 printf(MIDI_FORMAT
, MIDI_CONTROL
, ev
->data
.control
.channel
, ev
->data
.control
.value
);
49 case SND_SEQ_EVENT_PITCHBEND
:
50 printf(MIDI_FORMAT
, MIDI_PITCH_BEND
, ev
->data
.control
.channel
, ev
->data
.control
.value
);
52 case SND_SEQ_EVENT_NOTEON
:
53 printf(MIDI_FORMAT
, MIDI_NOTE_ON
, ev
->data
.control
.channel
, ev
->data
.note
.note
);
55 case SND_SEQ_EVENT_NOTEOFF
:
56 printf(MIDI_FORMAT
, MIDI_NOTE_OFF
, ev
->data
.control
.channel
, ev
->data
.note
.note
);
59 fflush(stdout
); fflush(stderr
);
60 snd_seq_free_event(ev
);
61 } while (snd_seq_event_input_pending(seq_handle
, 0) > 0);
64 int main(int argc
, char *argv
[]) {
66 snd_seq_t
*seq_handle
;
70 seq_handle
= open_seq();
71 npfd
= snd_seq_poll_descriptors_count(seq_handle
, POLLIN
);
72 pfd
= (struct pollfd
*)alloca(npfd
* sizeof(struct pollfd
));
73 snd_seq_poll_descriptors(seq_handle
, pfd
, npfd
, POLLIN
);
75 fprintf(stderr
, "COMMAND:CHANNEL:NOTE\nCommands are described on http://www.ec.vanderbilt.edu/computermusic/musc216site/MIDI.Commands.html\n\n");
77 if (poll(pfd
, npfd
, 100000) > 0) {
78 midi_action(seq_handle
);