[安卓/flutter]给Media3.exoplayer编译扩展ffmpeg解码器

/ 2,988评论 / 22941阅读 / 2点赞

前言

引用文档

准备

配置NDK 、cmdtools、SDKManager

cd {你想放NDK的目录}
wget {官网复制Linux版的下载链接}
unzip {刚刚下载的zip文件}
cd {cmdline-tools目录}/bin
sudo ./sdkmanager --licenses --sdk_root={你的NDK的根目录}

编译ffmpge

NDK_PATH="$(pwd)"
cd {你想放Media3.decoder_ffmpeg的目录}
git clone https://github.com/androidx/media --depth 1
cd media
FFMPEG_MODULE_PATH="$(pwd)/libraries/decoder_ffmpeg/src/main"
Lunux执行:
HOST_PLATFORM="linux-x86_64"

MacOX执行:
HOST_PLATFORM="darwin-x86_64"
ANDROID_ABI=21
cd {你想放ffmpge源码的目录}
git clone git://source.ffmpeg.org/ffmpeg && \ cd ffmpeg && \ git checkout release/6.0 && \ FFMPEG_PATH="$(pwd)"
ENABLED_DECODERS=(vorbis opus flac alac pcm_mulaw pcm_alaw mp3 amrnb amrwb aac ac3 eac3 dca mlp truehd)
cd "${FFMPEG_MODULE_PATH}/jni"
ln -s "$FFMPEG_PATH" ffmpeg
./build_ffmpeg.sh \ "${FFMPEG_MODULE_PATH}" "${NDK_PATH}" "${HOST_PLATFORM}" "${ANDROID_ABI}" "${ENABLED_DECODERS[@]}"
cd {开头放Media3.decoder_ffmpeg的目录}
./gradlew lib-decoder-ffmpeg:assembleRelease

项目引入ffmpge的aar包


dependencies {
    implementation(fileTree('libs'))
}
import java.util.zip.ZipEntry
import java.util.zip.ZipFile

// 把aar拷贝进入主项目的方法 com.example.android_control换成你自己的插件包名
// * 只修改下面这一行的参数就可以了
copyAar2Host('com.example.android_control')

// 拷贝aar的方法
static aarFileCopy(String srcPath,String desPath) {
    System.out.println("copy aar from <<${srcPath}>> to <<${desPath}>>")
    try {
        FileInputStream fis = new FileInputStream(srcPath)
        FileOutputStream fos = new FileOutputStream(desPath)
        byte[] data = new byte[1024*8]
        int len = 0
        while ((len = fis.read(data))!=-1) {
            fos.write(data,0,len)
        }
        fis.close()
        fos.close()
    }catch(Exception e) {
        e.printStackTrace()
    }
}

void copyAar2Host(String pluginGroup) {
    Project currentProject = null
    Project appProject = null
    rootProject.allprojects.each {
        p->
            boolean  isApp = p.plugins.hasPlugin("com.android.application")
            println("<<${p.name}>> isHost ? ${isApp}")
            if (p.group == pluginGroup) {
                currentProject = p
                println("Plugin project name is $currentProject")
            }
            if(isApp) {
                appProject = p
                println("Host project name is <<${p.name}>>")
            }
    }
    Set<File> aarFiles = new HashSet<File>()
    if (appProject != null && currentProject != null) {
        File libs = new File("${currentProject.projectDir}","libs")
        if(libs.isDirectory()) {
            libs.listFiles().each {
                f->
                    if(f.name.endsWith(".aar")) {
                        println("The aar file name to be copied is <<${f.name}>>")
                        aarFiles.add(f)
                    }

            }
        }
        if (!aarFiles.isEmpty()) {
            File applibs = new File("${appProject.projectDir}${File.separator}libs")
            if(!applibs.isDirectory()) {
                applibs.mkdirs()
            }
            aarFiles.each {
                f->
                    File copyAar = new File("${appProject.projectDir}${File.separator}libs",f.name)
                    if(!copyAar.exists()) {
                        copyAar.createNewFile()
                        aarFileCopy(f.path,copyAar.path)
                    } else {

                    }
            }
            appProject.dependencies {
                implementation fileTree(dir:"${appProject.projectDir}${File.separator}libs",include:["*.jar","*.aar"])
            }
        }
    }
}

repositories{
    flatDir {
        dirs 'libs'
    }
}
apply plugin: 'com.android.library'
// 在这里插入下面这一行
apply from: './aar_tools.gradle'

// 然后找到dependencies块,
dependencies {
    // 这一行导入刚刚libs目录内的ffmpge的arr包

    compileOnly(fileTree("libs"))
    // 这里用于解决用android studio打开项目的android目录时里面的java/kotlin文件的import都是灰色的问题
    compileOnly files("$flutterRoot/bin/cache/artifacts/engine/android-arm/flutter.jar")
    compileOnly("androidx.annotation:annotation:1.3.0")
}

在代码里引入ffmpeg


import androidx.media3.decoder.ffmpeg.FfmpegAudioRenderer;

class FfmpegRenderersFactory extends DefaultRenderersFactory {
    public FfmpegRenderersFactory(Context context) {
        super(context);
        setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON);
    }

    @Override
    protected void buildAudioRenderers(Context context, int extensionRendererMode, MediaCodecSelector mediaCodecSelector, boolean enableDecoderFallback, AudioSink audioSink, Handler eventHandler, AudioRendererEventListener eventListener, ArrayList<Renderer> out) {
        out.add(new FfmpegAudioRenderer(eventHandler, eventListener, audioSink));
        super.buildAudioRenderers(context, extensionRendererMode, mediaCodecSelector, enableDecoderFallback, audioSink, eventHandler, eventListener, out);
    }
}

ExoPlayer.Builder builder = new ExoPlayer.Builder(context);
// 添加ffmpeg

builder.setRenderersFactory(new FfmpegRenderersFactory(context));
ExoPlayer player = builder.build();
  1. Robertten说道:

    cheap medications: giant food store pharmacy hours – united pharmacy cialis

  2. JosephTycle说道:

    online shopping pharmacy india buy prescription drugs from india online pharmacy india

  3. JosephTycle说道:

    mexican pharmaceuticals online buying prescription drugs in mexico online п»їbest mexican online pharmacies

  4. JosephTycle说道:

    albertsons pharmacy femara online pharmacy generic cialis india pharmacy

  5. Arthurcig说道:

    https://mexicopharmacy.cheap/# reputable mexican pharmacies online

  6. MauriceSig说道:

    buy prescription drugs from india: cheapest online pharmacy india – top 10 pharmacies in india

  7. Robertten说道:

    indian pharmacies safe: indian pharmacy online – best online pharmacy india

  8. MauriceSig说道:

    mexican mail order pharmacies: buying prescription drugs in mexico – buying prescription drugs in mexico online

  9. Robertten说道:

    cheapest online pharmacy india: п»їlegitimate online pharmacies india – buy medicines online in india

  10. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в новосибирске
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. MauriceSig说道:

    indian pharmacies safe: india pharmacy mail order – indian pharmacy online

  12. MauriceSig说道:

    indianpharmacy com: indian pharmacy – indian pharmacy

  13. Arthurcig说道:

    https://indianpharmacy.company/# top 10 pharmacies in india

  14. Robertten说道:

    birth control: rx meaning in pharmacy – Aristocort

  15. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: замена стекла на планшете
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  16. Robertten说道:

    custom rx pharmacy: Gyne-Lotrimin – uk online pharmacy viagra

  17. Robertten说道:

    top online pharmacy india: buy medicines online in india – buy medicines online in india

  18. MauriceSig说道:

    pharmacy express viagra cialis levitra vpxl: domperidone us pharmacy – rx america pharmacy help desk

  19. Robertten说道:

    india pharmacy mail order: Online medicine order – online shopping pharmacy india

  20. JosephTycle说道:

    online pharmacy fluoxetine propranolol indian pharmacy tesco pharmacy viagra prices

  21. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в краснодаре

  22. MauriceSig说道:

    purple pharmacy mexico price list: mexico drug stores pharmacies – mexican pharmaceuticals online

  23. Robertten说道:

    global pharmacy rx: inhouse pharmacy finpecia – buy tetracycline online pharmacy

  24. JosephTycle说道:

    pentasa online pharmacy Sinemet boots pharmacy antibiotic eye drops chloramphenicol

  25. Arthurcig说道:

    https://mexicopharmacy.cheap/# medication from mexico pharmacy

  26. Arthurcig说道:

    http://indianpharmacy.company/# top 10 online pharmacy in india

  27. MauriceSig说道:

    mexico drug stores pharmacies: п»їbest mexican online pharmacies – buying prescription drugs in mexico

  28. JosephTycle说道:

    tadalafil generic pharmacy authentic cialis online pharmacy online pharmacy tegretol xr

  29. Arthurcig说道:

    https://mexicopharmacy.cheap/# mexican border pharmacies shipping to usa

  30. Arthurcig说道:

    http://pharmbig24.com/# safeway pharmacy

  31. I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post

  32. Drstowoola说道:

    mexican pharmacy online medications: provigil pharmacy – kamagra pharmacy uk

  33. Профессиональный сервисный центр по ремонту фото техники от зеркальных до цифровых фотоаппаратов.
    Мы предлагаем: диагностика и ремонт фотоаппаратов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  34. EasydrAcura说道:

    live pharmacy continuing education online: us pharmacy online – safeway pharmacy hours

  35. Drstowoola说道:

    precision pharmacy omeprazole: humana rx pharmacy – warfarin audit pharmacy

  36. Drstowoola说道:

    can you buy viagra at a pharmacy: rx discount pharmacy dade city fl – Prevacid

  37. EasydrAcura说道:

    amoxicillin boots pharmacy: norvasc online pharmacy – uk pharmacy online

  38. EasydrAcura说道:

    boots pharmacy propecia: tesco pharmacy doxycycline cost – buy hcg online pharmacy

  39. Techarp说道:

    Techarp This is my first time pay a quick visit at here and i am really happy to read everthing at one place

  40. mediaticas说道:

    I just could not depart your web site prior to suggesting that I really loved the usual info an individual supply in your visitors Is gonna be back regularly to check up on new posts

  41. allegheny county real estate I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will

  42. EasydrAcura说道:

    caremark online pharmacy: pharmacy sell viagra in malaysia – mexican pharmacy online reviews

  43. Drstowoola说道:

    triamcinolone cream online pharmacy: diamox pharmacy – propecia usa pharmacy

  44. EasydrAcura说道:

    viagra india pharmacy: certified online pharmacy cialis – stromectol pharmacy

  45. EasydrAcura说道:

    metoclopramide online pharmacy: mirtazapine pharmacy – xenical malaysia pharmacy

  46. Drstowoola说道:

    proscar inhouse pharmacy: wellbutrin pharmacy online – Feldene

  47. I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100 sure. Any recommendations or advice would be greatly appreciated. Cheers

  48. Drstowoola说道:

    generic propecia united pharmacy: your pharmacy ibuprofen – methotrexate prices pharmacy

  49. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервис центры бытовой техники москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  50. Hey would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most. Can you recommend a good hosting provider at a honest price? Thanks a lot, I appreciate it!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注