1)把编译生成的so库复制到libs文件夹下,同时把include里面的头文件也复制到libs文件夹下。
2)在build.gradle中添加一下代码
defaultConfig {
applicationId "com.houde.ffmpeg.test"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
abiFilters 'armeabi-v7a'
}
}
sourceSets{
main{
jniLibs.srcDirs = ['libs']
}
}
ndk{
abiFilters 'armeabi-v7a'
}
}
3)在CMakeList.txt中添加一下代码
include_directories(libs/include)
set(DIR ${CMAKE_SOURCE_DIR}/libs)
add_library(avcodec
SHARED
IMPORTED)
set_target_properties(avcodec
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libavcodec.so)
add_library(avdevice
SHARED
IMPORTED)
set_target_properties(avdevice
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libavdevice.so)
add_library(avformat
SHARED
IMPORTED)
set_target_properties(avformat
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libavformat.so)
add_library(avutil
SHARED
IMPORTED)
set_target_properties(avutil
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libavutil.so)
add_library(postproc
SHARED
IMPORTED)
set_target_properties(postproc
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libpostproc.so)
add_library(swresample
SHARED
IMPORTED)
set_target_properties(swresample
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libswresample.so)
add_library(swscale
SHARED
IMPORTED)
set_target_properties(swscale
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libswscale.so)
add_library(avfilter
SHARED
IMPORTED)
set_target_properties(avfilter
PROPERTIES IMPORTED_LOCATION
${DIR}/armeabi-v7a/libavfilter.so)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp)
target_link_libraries( # Specifies the target library.
native-lib
avfilter
avcodec
avdevice
avformat
avutil
postproc
swresample
swscale
# Links the target library to the log library
# included in the NDK.
${log-lib})
4)检查配置的so是否正确,在native-lib.cpp文件中引入libavcodec/avcodec.h,修改返回的字符串内容:
std::string hello = avcodec_configuration();
return env->NewStringUTF(hello.c_str());
显示结果:
错误记录:
1)ffmpeg函数不能被识别
编译是出现" undefined reference to 'avcodec_register_all()"和“Error:(15) undefined reference to 'avcodec_configuration()”,错误如下
Error:(15) undefined reference to 'avcodec_register_all()'
Error:(15) undefined reference to 'avcodec_configuration()'
这是因为ffmpeg是一个纯C语言编写的库,使用C++调用C代码时候,需要使用“extern “C””包围头文件“avcodec.h”和相关代码,如下:
#include <jni.h>
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
#include "libavcodec/avcodec.h"
#include "libavutil/avutil.h"
JNIEXPORT jstring JNICALL
Java_com_houde_ffmpeg_test_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = avcodec_configuration();
return env->NewStringUTF(hello.c_str());
}
#ifdef __cplusplus
};
#endif
参考文章:
https://www.jianshu.com/p/435bb46b33a9
https://blog.csdn.net/eieihihi/article/details/74153201