Search code examples
androidc++audiojava-native-interfacerecording

Send/Receive audio arrays between Java-Android and JNI


I am new in the Android programming world and I have already made a full search on the Internet about the JNI implementation in Android. By the way, there are lots of ways to do it, and I don't find too much documentation about DSP in C/C++ for Android.

I have already got the audio data from a recording (PCM to float), and I would like to send the data to a C/C++ function to process this data. After the transformation I would like to return the array to the Java activity to playback the result. Is there any simple example or documentation about sending and receiving arrays with the JNI?

I am using Windows 7, Eclipse and Cygwin.

Thank you in advance


Solution

  • Should be quite simple,

    To transfer a byteArray from Java to C++ you can consider the following example :

    Step 1: in the java class which will call the native method declare the method (in my example a simple zip)

    private native byte[] jniZipString(byte[] unpackedData, int datasize);
    

    Step 2: in c++ generate the header and implementation using javah.exe [note] call javah from the bin/classes foler (since your coding for android

    javah -jni com.example.JavaClassWithNativeMethods
    

    Step 3: in C++ receive the byte array and covert to C++ bytearray

    jbyte* tempPointer = env->GetByteArrayElements(jInput, 0);
    const char* cinput = (const char*) tempPointer;
    int dataSize = (int)env->GetArrayLength(jInput)
    

    Step 4: in process your data

    whatever you do to process the bytearray
    

    Step 5: return the resulting byte array to java

    jbyteArray result = (env)->NewByteArray(newDataSize);
    (env)->SetByteArrayRegion(result, 0, newDataSize, (jbyte *) processedCharArray); 
    return result;