新建c++项目
把编译出来的.a静态库和.h文件拷贝到项目中
9288878fbed66c49b76eb61ce6c32b3a.png 1d9c0fd65dfccc4d96669fd946e4fb50.png
修改build.gradle文件
android {
compileSdkVersion 29
buildToolsVersion "29.0.1"
defaultConfig {
applicationId "com.example.ffmpegapplication"
minSdkVersion 25
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
abiFilters 'armeabi-v7a'
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
version "3.10.2"
}
}
}
修改CMakeList文件,把静态库打包到我们的so中
注意链接顺序
cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
native-lib
SHARED
native-lib.cpp)
include_directories(include)
#set(my_lib_path ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI})
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -L${my_lib_path}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -L${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}")
find_library( # Sets the name of the path variable.
log-lib
log)
target_link_libraries( # Specifies the target library.
native-lib
avcodec avfilter avformat avutil swresample swscale
${log-lib})
后面我们就可以修改我们的cpp文件,调用ffmpeg里面的方法了
#include <jni.h>
#include <string>
extern "C" {
#include <libavcodec/avcodec.h>
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_ffmpegapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(av_version_info());
}
这里会打印ffmpeg的版本号
注意:
上面的代码中CMakeLists.txt文件是在根目录的,也就是说和build.gradle同级
cab984dce465d340b1984d0763db66a4.png
有的项目创建后,是在cpp目录下的
8add50c51ef7264eb7a6dbb53436687a.png
这样的话,CMAKE_CXX_FLAGS这个参数里,lib库的路径就要修改一下
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -L${CMAKE_SOURCE_DIR}/../../../libs/${ANDROID_ABI}")
因为,通过打印
message(WARNING "source Directory= ${CMAKE_SOURCE_DIR}")
得到的是:
source Directory= E:/workspace5_0/robot/FfmpegApplication/app/src/main/cpp
网友评论