Thursday, August 10, 2017

Integration of an Android App with Custom library

  1. Android App should have "Include C++ Support" checked.
  2. Unzip Trillbit.zip inside <App_Name> folder.
  3. Open app/CMakeLists.txt . Add the following lines to include "Trill" library and headers:
set(trillbit_DIR ../trillbit)

add_library(lib_itpp SHARED IMPORTED)
set_target_properties(lib_itpp PROPERTIES IMPORTED_LOCATION
${trillbit_DIR}/lib/${ANDROID_ABI}/libitpp.so)

add_library(lib_trill SHARED IMPORTED)
set_target_properties(lib_trill PROPERTIES IMPORTED_LOCATION
${trillbit_DIR}/lib/${ANDROID_ABI}/libtrill.so)

add_library( <your_cpp_filename>
             SHARED
             src/main/cpp/<your_cpp_filename>.cpp )

target_include_directories(<your_cpp_filename> PRIVATE ${trillbit_DIR}/include)

target_link_libraries(<your_cpp_filename>
                      android
                      lib_itpp
                      lib_trill)
4. Open app/build.gradle and add following line after buildTypes:
sourceSets {
 main {
  // let gradle pack the shared library into apk
  jniLibs.srcDirs = ['../trillbit/lib']
 }
}
5. Open src/main/cpp/<your_cpp_filename>.cpp for JNI implementation. Here is a sample code to show how to find trigger in recorded audio data using Trill library.
#include <jni.h>
#include <string>
#include <trigger.h>

extern "C"
jboolean
Java_com_trillbit_trillapp_MainActivity_isTriggerFound(
JNIEnv* env,
jobject, jshortArray data_arr, jint data_arr_len) {

//normalize raw recorded audio data and put into a string
std::string data_str;
for(jint i = 0; i < data_arr_len; i++)
{
 char dataInterim[30];
 sprintf(dataInterim,"%f, ", data_arr[i]/pow(2,10)); data_str.append(dataInterim);
}

Trigger tg;
return tg.isFound(data_str);
}

5. Open src/main/java/MainActivity.java. Following sample code shows how Trillbit's library is accessible to Java code through JNI.




static {
 System.loadLibrary("<your_cpp_filename>");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
   ....
   ....
   short[] buffer = new short[BUFFER_SIZE];
   recorder.read(buffer, 0, BUFFER_SIZE);
   ....
   if (isTriggerFound(buffer, buffer.length)) {

   }
   .....
}
// Put this definition at the end of the file
public native boolean isTriggerFound(short[] data, int data_len);

No comments:

Post a Comment