Reading MIDI Port from Kotlin Native using rtmidi in Windows

Submitted by Dickens A S on Sun, 08/08/2021 - 01:48

This article demonstrates how a MIDI port can be read from Kotlin native code via rtmidi library

Kotlin Code

package plot

import kotlin.native.concurrent.*
import platform.posix.sleep
import kotlinx.cinterop.*
import kotlin.text.*
import rtmidi.*


lateinit var midiPtr: RtMidiInPtr

fun midi_callback(
                 timeStamp: Double, 
                 message: CArrayPointer<UByteVar>,
                 messageSize: size_t, 
                 userData: COpaquePointerVar
) = memScoped {
    initRuntimeIfNeeded()
    
    var key = message[1].toString()
    println(key)
}

fun main() {
    midiPtr = rtmidi_in_create_default()!!
    
    rtmidi_in_set_callback(midiPtr, staticCFunction {  
            timeStamp: Double, 
            message: CArrayPointer<UByteVar>,
            messageSize: size_t, 
            userData: COpaquePointerVar
            -> midi_callback( timeStamp, message, messageSize, userData  )
        }.reinterpret(),
        null
    )

    var c = rtmidi_get_port_count(midiPtr)
    
    for(i in 0..c.toInt()-1){
        var portName = rtmidi_get_port_name(midiPtr, i.toUInt())!!.toKString()
        rtmidi_open_port(
           midiPtr!!, 
           i.toUInt(), 
           portName
        )
    }
    println("waiting for 5 seconds")
    sleep(5)
    println("closing all the midi ports")
    rtmidi_in_cancel_callback(midiPtr)
    rtmidi_close_port(midiPtr)
    rtmidi_in_free(midiPtr)
}

When you run the code, it waits for 5 seconds,

Press any key in your MIDI keyboard, it will print the numeric value of that key as below

Refer this article android-as-midi-input-to-pc for setting android app as USB MIDI input device for a PC

Output

> Task :app:runDebugExecutableLibgnuplot
waiting for 5 seconds
21
21
closing all the midi ports

Finished

 

Add new comment