How to read usb midi device input as music symbol by using c under linux system

Joined
Mar 19, 2024
Messages
3
Reaction score
1
// Linux MIDI input driver, protocol 1.0, there is no need to upgrade to protocol 2.0
// Author: yingshaoxo
// Run it in root shell
// gcc main.c -o main.run
// ./main.run

#include <sys/soundcard.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define MIDI_DEVICE "/dev/midi1"
//#define MIDI_DEVICE "/dev/dmmidi1"
//#define MIDI_DEVICE "/dev/snd/midiC1D0"

int main(void) {
unsigned char inpacket[4];

// first open the sequencer device for reading.
int seqfd = open(MIDI_DEVICE, O_RDONLY);
if (seqfd == -1) {
printf("Error: cannot open %s\n", MIDI_DEVICE);
exit(1);
}

// now just wait around for MIDI bytes to arrive and print them to screen.
while (1) {
read(seqfd, &inpacket, sizeof(inpacket));

if (inpacket[0] == 144) {
printf("Pressed: ");
printf("%d\n", inpacket[1]);
} else {
printf("Released: ");
printf("%d\n\n", inpacket[1]);
}

//printf("strongth: %d", inpacket[2]);
}

return 0;
}
 

SeaGtGruff

I meant to play that note!
Moderator
Joined
Jun 6, 2014
Messages
4,117
Reaction score
1,738
As someone who once tried dabbling in MIDI app programming, it's nice to see someone else sharing like this.
 
Joined
Mar 19, 2024
Messages
3
Reaction score
1
I also made a python version:

Python:
# Author: yingshaoxo
# Python: 3.5
# midi usb protocol: 1.0  ;  There has no need to upgrade to 2.0

device_name = "/dev/midi1" # "/dev/dmmidi1" # "/dev/snd/midiC1D0"

while True:
    with open(device_name, "rb") as f:
        bytes_list = [None] * 3
        for index in range(3):
            bytes_list[index] = f.read(1)
        int_list = [int.from_bytes(one, "big") for one in bytes_list]

        the_key = int_list[1]
        the_strongth = int_list[2]
        print("              strongth:", the_strongth)
        if int_list[0] == 144:
            print("pressed:", the_key)
        else:
            print("released:", the_key)
            print("\n\n-------\n")
        print()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
14,078
Messages
86,957
Members
13,166
Latest member
golek

Latest Threads

Top