7ee730e83a90c646609badb0e14b367e39670183
[mirrors/Programs.git] / c / ghetto-sound-system / midi-rx.c
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
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <alsa/asoundlib.h>
9
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 "%d:%d:%d\n"
15
16 snd_seq_t *open_seq();
17 void midi_action(snd_seq_t *seq_handle);
18
19 snd_seq_t *open_seq() {
20
21 snd_seq_t *seq_handle;
22 int portid;
23
24 if (snd_seq_open(&seq_handle, "hw", SND_SEQ_OPEN_DUPLEX, 0) < 0) {
25 fprintf(stderr, "Error opening ALSA sequencer.\n");
26 exit(1);
27 }
28 snd_seq_set_client_name(seq_handle, "ALSA Sequencer Pipe");
29 if ((portid = snd_seq_create_simple_port(seq_handle, "ALSA Sequencer Pipe",
30 SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE,
31 SND_SEQ_PORT_TYPE_APPLICATION)) < 0) {
32 fprintf(stderr, "Error creating sequencer port.\n");
33 exit(1);
34 }
35 return(seq_handle);
36 }
37
38 void midi_action(snd_seq_t *seq_handle) {
39
40 snd_seq_event_t *ev;
41
42 do {
43 snd_seq_event_input(seq_handle, &ev);
44 switch (ev->type) {
45 case SND_SEQ_EVENT_CONTROLLER:
46 printf(MIDI_FORMAT, MIDI_CONTROL, ev->data.control.channel, ev->data.control.value);
47 break;
48 case SND_SEQ_EVENT_PITCHBEND:
49 printf(MIDI_FORMAT, MIDI_PITCH_BEND, ev->data.control.channel, ev->data.control.value);
50 break;
51 case SND_SEQ_EVENT_NOTEON:
52 printf(MIDI_FORMAT, MIDI_NOTE_ON, ev->data.control.channel, ev->data.note.note);
53 break;
54 case SND_SEQ_EVENT_NOTEOFF:
55 printf(MIDI_FORMAT, MIDI_NOTE_OFF, ev->data.control.channel, ev->data.note.note);
56 break;
57 }
58 snd_seq_free_event(ev);
59 } while (snd_seq_event_input_pending(seq_handle, 0) > 0);
60 }
61
62 int main(int argc, char *argv[]) {
63
64 snd_seq_t *seq_handle;
65 int npfd;
66 struct pollfd *pfd;
67
68 seq_handle = open_seq();
69 npfd = snd_seq_poll_descriptors_count(seq_handle, POLLIN);
70 pfd = (struct pollfd *)alloca(npfd * sizeof(struct pollfd));
71 snd_seq_poll_descriptors(seq_handle, pfd, npfd, POLLIN);
72
73 fprintf(stderr, "COMMAND:CHANNEL:NOTE\nCommands are described on http://www.ec.vanderbilt.edu/computermusic/musc216site/MIDI.Commands.html\n\n");
74 while (1) {
75 if (poll(pfd, npfd, 100000) > 0) {
76 midi_action(seq_handle);
77 }
78 }
79 }
This page took 0.254607 seconds and 3 git commands to generate.