Android Studio Audio Player [Part 7] Integrating c++ codes in.
This is is part 7 of the series.
- Setting up the interface.
- Playing, pausing, resume, stopping an audio.
- Loading the audio into data array.
- Plotting the data into a waveplot canvas for visualisation.
- Enable scrolling of the canvas.
- Having a slider to show the current wave time.
- Integrating c++ codes in.
Install & Configure NDK
If you downloaded it before, include it in your local.properties file like this
Under Tools -> SDK Manager, install NDK if you have not already done so.
Install & Configure CMake
Add in the CMake version to your build.gradle.
Make a new directory cpp, under your app/src/main directory.
Create a new file CMakeLists.txt in the cpp directory if it’s not already there. Follow this to populate the CMakeLists.txt.
Link Gradle
https://developer.android.com/studio/projects/gradle-external-native-builds
Go to Android view, and from the app, right click Link C++ Project with Gradle
This pop up will show, and select Build System CMake.
Find the path to the CMakeList.txt that you created above, and link it to the Project Path.
Now, the cmake will be created in your build.gradle file.
Go back to Project View, and create a C++ Source File called native-lib.cpp. You can now press Run, to process whatever is in your c++ script.
If you face this error, it is because it should be a relative path to your CMakeList.txt. So change it from “src/main/cpp/native-lib.cpp” to “native-lib.cpp” instead.
Compiling CMakeList.txt
/** c++ Setup */
static {
System.loadLibrary("native-lib");
}
Call this in your MainActivity.java
Setup the c++ file
Now we try to define a function to call from the c++ file. But we have this error.
A workaround is to define a function with JNI definitions, so that in the MainActivity.java, it will know that this native-lib.cpp file uses JNI, and will help you create the necessary linkage for integrating the functions with MainActivity.java.
#include <jni.h>
#include <string.h>extern "C" JNIEXPORT jstring JNICALL
Java_com_example_templatec_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
Now, you can simply click on this, and it will create a function for you in the native-lib.cpp file:
It seems that in order to link with MainActivity.java, we require
extern "C"
JNIEXPORT jstring JNICALL
and some template definitions.
Similarly, if you define a function with data structures, it will help you to define it in the cpp file accordingly.
ArrayList in Java <-> Vector in cpp
https://gist.github.com/qiao-tw/6e43fb2311ee3c31752e11a4415deeb1
To try and test