|
| 1 | +#include <jni.h> |
| 2 | +#include <string> |
| 3 | +#include "RtMidi.h" |
| 4 | + |
| 5 | +static RtMidiIn* midiLib = new RtMidiIn( RtMidi::Api::ANDROID_AMIDI ); |
| 6 | +static jobject callbackObj = NULL; |
| 7 | +static jmethodID callbackMethod; |
| 8 | +static JavaVM* jvm; |
| 9 | + |
| 10 | +extern "C" JNIEXPORT jobjectArray JNICALL |
| 11 | +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_portNames( |
| 12 | + JNIEnv* env, |
| 13 | + jobject /* this */) { |
| 14 | + |
| 15 | + auto portCount = midiLib->getPortCount(); |
| 16 | + auto names = env->NewObjectArray(portCount, env->FindClass("java/lang/String"), NULL); |
| 17 | + |
| 18 | + for (int i=0; i<portCount; i++) { |
| 19 | + auto name = midiLib->getPortName(i); |
| 20 | + env->SetObjectArrayElement(names, i, env->NewStringUTF(name.c_str())); |
| 21 | + } |
| 22 | + |
| 23 | + return names; |
| 24 | +} |
| 25 | + |
| 26 | +static void midicallback( double deltatime, std::vector< unsigned char > *message, void */*userData*/ ) { |
| 27 | + unsigned int numBytes = message->size(); |
| 28 | + |
| 29 | + JNIEnv* env; |
| 30 | + jvm->AttachCurrentThread(&env, NULL); |
| 31 | + |
| 32 | + // Allocate the Java array and fill with received data |
| 33 | + jbyteArray ret = env->NewByteArray(numBytes); |
| 34 | + env->SetByteArrayRegion(ret, 0, numBytes, (jbyte*)message); |
| 35 | + |
| 36 | + // send it to the (Java) callback |
| 37 | + env->CallVoidMethod(callbackObj, callbackMethod, deltatime, ret); |
| 38 | +} |
| 39 | + |
| 40 | +extern "C" |
| 41 | +JNIEXPORT void JNICALL |
| 42 | +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_openPort( |
| 43 | + JNIEnv *env, |
| 44 | + jobject /* this */, |
| 45 | + jint port, |
| 46 | + jobject listener) { |
| 47 | + |
| 48 | + env->GetJavaVM(&jvm); |
| 49 | + |
| 50 | + midiLib->setCallback( midicallback ); |
| 51 | + midiLib->openPort(port); |
| 52 | + |
| 53 | + if (callbackObj) env->DeleteGlobalRef(callbackObj); |
| 54 | + callbackObj = env->NewGlobalRef(listener); |
| 55 | + callbackMethod = env->GetMethodID(env->GetObjectClass(listener), "onMidiMessage", "(D[B)V"); |
| 56 | +} |
| 57 | + |
| 58 | +extern "C" JNIEXPORT void JNICALL |
| 59 | +Java_com_rtmidi_yellowlab_midireader_MidiViewModel_closePort( |
| 60 | + JNIEnv *env, |
| 61 | + jobject /* this */) { |
| 62 | + |
| 63 | + midiLib->closePort(); |
| 64 | + if (callbackObj) env->DeleteGlobalRef(callbackObj); |
| 65 | + callbackObj = NULL; |
| 66 | + callbackMethod = NULL; |
| 67 | +} |
0 commit comments