一、Android Studio3.5.2创建C++ Android项目
1、新建一个工程一直点击下一步,都是选默认的,添加一个工程。
2、添加NDK路径
点击菜单File->Project Structure
3、Android SDK中安装CMake和LLDB
4、添加module(library)(New->Module)
5、把myplayer的module添加到app里面去
二、myplayer Module添加C++支持
1、移动项目中app下面的cpp到Module根目录下
2、剪切 build.gradle 中externalNativeBuild 到myplayer module 的 build.gradle 中
externalNativeBuild {
cmake {
cppFlags ""
abiFilters 'arm64-v8a', "x86"
}
}
3、剪切 build.gradle 中到 module 的 build.gradle 中
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
4、创建测试java文件Demo.java
5、调用java本地方法
public class MainActivity extends AppCompatActivity {
private Demo demo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
demo = new Demo();
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(demo.stringFromJNI());
}
三、添加ffmpeg动态库
1、module cpp文件夹中创建include文件夹,并添加ffmpeg中include里
面的所有文件
2、module main文件夹中创建jniLibs,复制arm64-v8a和x86的.so库到jniLibs中
3、添加ffmpeg动态库
externalNativeBuild {
cmake {
cppFlags ""
abiFilters 'arm64-v8a', "x86"
}
}
//在defaultConfig同级中添加
sourceSets {
main {
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
四、cmakelist中配置ffmpeg
1、导入include路径
include_directories(${CMAKE_SOURCE_DIR}/include)
2、设置动态库路径(如:libavcodec-57.so)
set_target_properties( avcodec-57
PROPERTIES IMPORTED_LOCATION
${CMAKE_SOURCE_DIR}/../../../src/main/jniLibs/${ANDROID_ABI}/libavcodec-57.so)
3、添加动态库
add_library( avcodec-57 SHARED IMPORTED)
4、链接动态库
target_link_libraries(
native-lib
avcodec-57
avformat-57
avutil-55
swresample-2
swscale-4
log)
5、java中加载动态库
static {
System.loadLibrary("native-lib");
System.loadLibrary("avcodec-57");
System.loadLibrary("avformat-57");
System.loadLibrary("avutil-55");
System.loadLibrary("swresample-2");
System.loadLibrary("swscale-4");
}
四、验证ffmpeg是否添加成功
extern "C"
JNIEXPORT jstring JNICALL
Java_com_wq_myplayer_Demo_stringFromJNI(JNIEnv *env, jobject thiz) {
// TODO: implement stringFromJNI()
std::string hello = av_version_info();
return env->NewStringUTF(hello.c_str());
}
测试结果如下: