音视频系列二 Android Studio配置ffmpeg(jni使用so库)

178 阅读1分钟

一 复制文件

android studio 创建jni工程,然后将ffmpeg编译后在android子目录下生成的so库和头文件拷到libs目录下,如下图
工程结构图片
注意,如果是放在其他目录下或者gradle版本低于4的需要在module的build.gradle文件中配置sourceSets,在defaultConfig这个范围中,如下图:

sourceSets libs改成你自己的位置

二 修改CMakeLists.txt

样例如下

cmake_minimum_required(VERSION 3.10.2)

project("bipplayer")
add_library(
        native-lib
        SHARED
        native-lib.cpp)

find_library( # Sets the name of the path variable.
        log-lib
        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

set(DIR ${CMAKE_SOURCE_DIR}/../../../libs)
include_directories(${DIR}/include)
add_library(avcodec
        SHARED
        IMPORTED)
set_target_properties(avcodec
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libavcodec.so)

add_library(avdevice
        SHARED
        IMPORTED)
set_target_properties(avdevice
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libavdevice.so)
add_library(avfilter
        SHARED
        IMPORTED)
set_target_properties(avfilter
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libavfilter.so)
add_library(avformat
        SHARED
        IMPORTED)
set_target_properties(avformat
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libavformat.so)
add_library(avutil
        SHARED
        IMPORTED)
set_target_properties(avutil
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libavutil.so)
add_library(postproc
        SHARED
        IMPORTED)
set_target_properties(postproc
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libpostproc.so)
add_library(swresample
        SHARED
        IMPORTED)
set_target_properties(swresample
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libswresample.so)
add_library(swscale
        SHARED
        IMPORTED)
set_target_properties(swscale
        PROPERTIES IMPORTED_LOCATION
        ${DIR}/arm64-v8a/libswscale.so)

target_link_libraries( # Specifies the target library.
        native-lib
        avcodec
        avdevice
        avfilter
        avformat
        avutil
        postproc
        swresample
        swscale
        # Links the target library to the log library
        # included in the NDK.
        ${log-lib})

主要就是通过 include_directories() 导入头文件,然后多次通过add_library()set_target_properties() 导入so库,然后在target_link_libraries() 中将上面添加的库链接进来

三 测试运行

修改native-lib.cpp如下

#include <jni.h>
#include <string>

extern "C" {
#include "libavcodec/avcodec.h"
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_github_welcomeworld_bipplayer_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = avcodec_configuration();
    return env->NewStringUTF(hello.c_str());
}

能正常跑起来那就集成成功,不能就根据报错解决问题。