[FFmpeg 戦闘] フラッターオーディオとビデオクロップ

著者:JianLee リンク:https ://www.jianshu.com/p/868c8536a9b2

flutter_ffmpegとは何ですか?

ffmpeg は、コマンド ラインを通じてオーディオとビデオを処理するオーディオおよびビデオ処理ライブラリです。MobileFFmpeg は、
モバイル側での ffmpeg の実装です。flutter_ffmpeg は、MobileFFmpeg のカプセル化です。はい、ffmpeg を使用して、flutter でオーディオとビデオを簡単に処理できます. 加工用です。flutter_ffmpeg には FFmpeg と FFprobe の 2 つの部分が含まれており、FFmpeg はオーディオとビデオの処理を担当し、FFprobe は主にオーディオとビデオのメディア情報のクエリを担当します。

flutter_ffmpeg アドレス

flutter_ffmpegの使用
ステップ 1: インストール
// 在pubspec.yaml的dependencies下添加:
  flutter_ffmpeg: ^0.3.1
ステップ 2: 構成

Androidプロジェクトでの設定

// 在工程目录下的 /android/build.gradle下添加
ext {
    
    
    flutterFFmpegPackage  = "full-lts" 
}

注: 上記の設定の「full-lts」は、flutter__ffmpeg の各リリース バージョンの登録です。手順については、公式ドキュメントを確認してください。説明しておきたいのは、flutter_ffmpeg には Main Release と LTS Release リリース パッケージの 2 つのリリース パッケージがあり、それらでサポートされる Android API レベル/iOS SDK およびハードウェア アーキテクチャが異なるということです。はより広くサポートされており、LTS サポートは MAIN より優れているため、LTS バージョンを使用することをお勧めします。
ここで問題が発生しました。full-lts エンコード形式を使用すると、サーバーにアップロードされたビデオが再生できません。
そこで私がここで使用するのは次のとおりです。

ext {
    
    
    flutterFFmpegPackage = "full-gpl-lts"
}

さらに、flutter_ffmpeg を使用したときにも同様の問題が発生しました。

Caused by: java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/app.domain.name-Lq_GxP1CfMArHTpLoII-YA==/base.apk"],nativeLibraryDirectories=[/data/app/app.domain.name-Lq_GxP1CfMArHTpLoII-YA==/lib/arm64, /data/app/app.domain.name-Lq_GxP1CfMArHTpLoII-YA==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]] couldn't find "libmobileffmpeg_abidetect.so"
        at java.lang.Runtime.loadLibrary0(Runtime.java:1011)
        at java.lang.System.loadLibrary(System.java:1657)
        at com.arthenica.mobileffmpeg.AbiDetect.<clinit>(Unknown Source:13)
        at com.arthenica.mobileffmpeg.AbiDetect.getNativeAbi(Native Method)
        at com.arthenica.mobileffmpeg.Config.<clinit>(Unknown Source:96)
        at com.arthenica.mobileffmpeg.Config.nativeFFmpegExecute(Native Method)
        at com.arthenica.mobileffmpeg.b.a(Unknown Source:0)
        at d.b.a.a.a.a(Unknown Source:31)
        at d.b.a.a.a.doInBackground(Unknown Source:2)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
        at java.lang.Thread.run(Thread.java:764) 

掃除すれば解決できるよ

flutter clean
flutter build [artificat]

gpl を使用して、トリミングされたビデオがデフォルトで x264 を使用するようにします (そうしないと、アップロードされたビデオを再生できないという問題が発生します)。詳細については、flutter_ffmpeg カプセル化エンコーディングを表示できます。

画像

画像.png

ステップ 3: 使用する

flutter_ffmpge は flutter 上の ffmpeg の実装です。ffmpeg はコマンド ラインを介してオーディオとビデオを編集するためのツールです。したがって、flutter_ffmpeg を使用するときは、当然のことながらいくつかのコマンドを実行して機能を実装します。具体的な使用方法については、 ffluter_ffmpegffmpegの公式ドキュメントを直接読むか、よりわかりやすいRuan Yifeng のドキュメントを参照してください。次に、flutter_ffmpeg で何ができるのかを主に見ていきます。

flutter_ffmpge では何ができるのでしょうか?

ビデオ情報を見る

オーディオやビデオの処理を行う場合、まず処理が成功したかどうか、効果が良いかどうかを知りたいのですが、その後、処理されたビデオの前後のパラメータを比較することしかできません。このビデオ処理ライブラリに詳細な情報を提供してもらってください。オーディオとビデオの情報、flutter_ffmpeg の FFProde はこれを非常にうまく実現でき、非常に便利です。

final FlutterFFprobe _flutterFFprobe = new FlutterFFprobe();

_flutterFFprobe.getMediaInformation("<file path or uri>").then((info) {
    
    
    print("Media Information");

    print("Path: ${
      
      info.getMediaProperties()['filename']}");
    print("Format: ${
      
      info.getMediaProperties()['format_name']}");
    print("Duration: ${
      
      info.getMediaProperties()['duration']}");
    print("Start time: ${
      
      info.getMediaProperties()['start_time']}");
    print("Bitrate: ${
      
      info.getMediaProperties()['bit_rate']}");
    Map<dynamic, dynamic> tags = info.getMediaProperties()['tags'];
    if (tags != null) {
    
    
        tags.forEach((key, value) {
    
    
            print("Tag: " + key + ":" + value + "\n");
        });
    }

    if (info.getStreams() != null) {
    
    
        List<StreamInformation> streams = info.getStreams();

        if (streams.length > 0) {
    
    
            for (var stream in streams) {
    
    
                print("Stream id: ${
      
      stream.getAllProperties()['index']}");
                print("Stream type: ${
      
      stream.getAllProperties()['codec_type']}");
                print("Stream codec: ${
      
      stream.getAllProperties()['codec_name']}");
                print("Stream full codec: ${
      
      stream.getAllProperties()['codec_long_name']}");
                print("Stream format: ${
      
      stream.getAllProperties()['pix_fmt']}");
                print("Stream width: ${
      
      stream.getAllProperties()['width']}");
                print("Stream height: ${
      
      stream.getAllProperties()['height']}");
                print("Stream bitrate: ${
      
      stream.getAllProperties()['bit_rate']}");
                print("Stream sample rate: ${
      
      stream.getAllProperties()['sample_rate']}");
                print("Stream sample format: ${
      
      stream.getAllProperties()['sample_fmt']}");
                print("Stream channel layout: ${
      
      stream.getAllProperties()['channel_layout']}");
                print("Stream sar: ${
      
      stream.getAllProperties()['sample_aspect_ratio']}");
                print("Stream dar: ${
      
      stream.getAllProperties()['display_aspect_ratio']}");
                print("Stream average frame rate: ${
      
      stream.getAllProperties()['avg_frame_rate']}");
                print("Stream real frame rate: ${
      
      stream.getAllProperties()['r_frame_rate']}");
                print("Stream time base: ${
      
      stream.getAllProperties()['time_base']}");
                print("Stream codec time base: ${
      
      stream.getAllProperties()['codec_time_base']}");

                Map<dynamic, dynamic> tags = stream.getAllProperties()['tags'];
                if (tags != null) {
    
    
                  tags.forEach((key, value) {
    
    
                    print("Stream tag: " + key + ":" + value + "\n");
                  });
                }
            }
        }
    }
});

ビデオ圧縮

  • フレームレートを変更する
ffmpeg -i Desktop/吉他.mp4  -r 20  Desktop/output1.mp4

-r 20: フレーム レートが 20fps に設定されていることを示します。

  • ファイルサイズを指定する
ffmpeg -i Desktop/吉他.mp4  -fs 15MB  Desktop/output1.mp4

fs 20: 最大ファイル サイズが 15 MB で
、ビデオの一部が切り取られていることを示します。この方法はお勧めできません。

  • 解像度を変更する
ffmpeg -i Desktop/1.mov -s vga Desktop/1.mp4

-s vga: 解像度を指定します。vga は 600*480 を表し、他の値に変更することもできます。

  • ビット レートを変更します。
    ビデオの元のビット レートは 2.1Mb/s で、圧縮は 1.5Mb/s です。
ffmpeg -i Desktop/1.mov -b:v 1.5M  Desktop/1.mp4

-b:v 1.5M: ビット レートを指定します。
-b:v: ビデオ ビット レートを指定します。
-b:a: オーディオ ビット レートを指定します
。 1.5M: ビット レート値 1.5M は 1.5Mb/s を意味します。

ビデオをクロップする

たとえば、私のプロジェクトでは、サーバーにアップロードされるビデオの長さを 60 秒以内に制御する必要がある関数を使用しています。

 String inputFilePath = inputFile.path;
                    String outputFilePath =
                        await FileUtils.outputFileNameStr(inputFile);
                    var ffmpeg = new FlutterFFmpeg();
                    ffmpeg
                        .execute(
                            "-i $inputFilePath -ss 0 -to 60 -c:v libx264 $outputFilePath")//这里是ffmpeg指令 裁剪60s视频
                        .then((rc) async {
    
    
                      if (rc == 0) {
    
    
                        //rc=0表示成功
                        //裁剪60s 转换 libx264
                      } else {
    
    
                        showToast('视频裁剪出现异常,请重试', context);
                        Navigator.pop(context);
                      }
                    });

ビデオ形式を変換する

var ffmpeg = new FlutterFFmpeg();
  Directory tempDir = await getTemporaryDirectory();;
  var tmpVideo = tempDir.path + '/1.webm';
  var cmd = '-i ${
      
      widget.tmpPath} $tmpVideo';
  print('命令是:'+cmd);
  ffmpeg.execute(cmd).then((rc) {
    
    
    print("处理的结果是:$rc");
    if(rc == 0) {
    
    
      initController(tmpVideo); //使用临时地址可以播放
    } else {
    
    
      print('处理失败');
    }
  });

以下に、一般的に使用される ffmpeg 命令をいくつか示します。

ビデオのトリミング

nから始めてm秒の長さのビデオを切り出します

// 从10s开始裁剪连续5s 也就是10-15s的视频
ffmpeg -i input.mp4 -ss 10 -t 5 output.mp4

n 秒から開始してビデオを m 秒に切り抜きます

// 从10s开始,裁剪到20秒
ffmpeg -i input.mp4 -ss 10 -to 20 output.mp4
フィルター

https://www.cnblogs.com/tocy/p/ffmpeg-filter-intro.html

2 つのビデオをオーバーレイする:
ffmpeg -i 1.mp4 -i douyin.mp4 -filter_complex " blend=all_mode='overlay':all_opacity=0.2" blend.mp4
100*100 のビデオをカットすると、新しいビデオの中心点が入力とビデオと一致します。
ffmpeg -i douyin.mp4  -vf "crop=100:100" crop.mp4
ビデオ上にフレーム ドローボックスを描画します
// [email protected] 50%的透明度红色
// t=1 线条的粗细 默认3  fill的话 自动填充
ffmpeg -i input.mp4 -vf "drawbox=10:10:30:30:[email protected]:t=1" output.mp4
ffmpeg -i input.mp4 -vf "drawbox=x=10:y=10:width=30:[email protected]:t=1" output.mp4
ビデオでグリッドを描画する
画尺寸是20*20的网格
ffmpeg -i 1.mp4 -vf "drawgrid=width=20:height=20:color=red" output.mp4
画2*2的网格
ffmpeg -i 1.mp4 -vf "drawgrid=width=iw/2:height=ih/2:color=red:t=1:[email protected]" output.mp4
ビデオのドローテキストに書き込む
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=red:text='hello world':alpha=0.8" font.mp4

//前五秒显示 
// gte(t\,5) 大于等于5秒
// between(t\,5\,10)5到10秒
// lt(t\, 5)小于5秒
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=red:text='hello world':enable='lt(t\,5)' " font.mp4

//水平居中 (w-text_w)/2
//垂直居中 (h-text_h)/2
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=#cccccc:text='hello world':x=(w-text_w)/2" font2.mp4

//向右对齐 
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=#cccccc:text='hello world':x=(w-text_w)" font2.mp4

// 水平垂直居中
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=#cccccc:text='hello world':x=(w-text_w)/2:y=(h-text_h)/2" font2.mp4

// 滚动文本
ffmpeg -i 99.mp4 -vf "drawtext=fontsize=32:fontcolor=#cccccc:text='hello world':x=(w-50*t)" font2.mp4
彩度/明るさ/コントラスト等
// contrast 对比度 -1000-1000
// brightness 亮度 -1.0-1.0
// saturation 饱和度 0.0-3.0
ffmpeg -i 1.mp4 -vf "eq=saturation=3:brightness=0.3:contrast=1000" output.mp4
フェードイン フェードアウト フェード
// 从第0帧开始到30帧淡入
ffmpeg -i 1.mp4 -vf "fade=t=in:s=0:n=30" output.mp4

// 从10秒开始淡出5秒
ffmpeg -i 1.mp4 -vf "fade=t=out:st=10:d=5" output.mp4
フレームレートfpsを調整する
ffmpeg -i 1.mp4 -vf "fps=fps=24" output.mp4
ビデオを水平方向に反転する
ffmpeg -i 1.mp4 -vf "hflip" output.mp4
逆行する
ffmpeg -i input.mp4 -vf "reverse" output.mp4
回転回転
旋转45度
ffmpeg -i input.mp4 -vf "rotate=PI/4"

转圈圈
ffplay -i 99.mp4 -vf "rotate=n*PI/3:c=red"

调整输出尺寸 修改输出宽度等于输入宽度的对角线
ffplay -i 99.mp4 -vf "rotate=n*PI/3:ow=hypot(iw, ih):oh=ow"
スケールスケール
ffplay -i 99.mp4 -vf "scale=100x100"
ffplay -i 99.mp4 -vf "scale=w=0.8*iw:h=0.8*ih"


// 宽度为100,iw较小的值 高度等比例缩小
ffplay -i 99.mp4 -vf "scale=w=min(100\,iw):h=-1"
マージ連結
// 视频的尺寸要一样大 如果不一样大的话 可以使用pad补边界 
ffmpeg -i 1.mp4 -i douyin.mp4 -i 3.1.mp4 -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[ov][oa]" -map "[ov]" -map "[oa]" -vsync 2 output.mp4

// 图片和视频合并 需要调整视频图片的尺寸和视频一样
ffmpeg -loop 1 -framerate 25 -t 5 -i logo.png -i 3.mp4 -filter_complex "[0]scale=1280x720[01];[01][1:v:0]concat=n=2:v=1[ov]" -map "[ov]" 33.mp4

ffmpeg -loop 1 -framerate 25 -t 5 -i logo.png -i 3.mp4 -filter_complex "[0]pad=w=1280:h=720:w=(1280-iw)/2:y=(720-ih)/2[01];[01][1:v:0]concat=n=2:v=1[ov]" -map "[ov]" 33.mp4

ffmpeg -loop 1 -framerate 29.42 -t 10 -i 1.s.jpg -i 1.mp4 -filter_complex "[0]scale=480:480, setsar=1[im];[1]scale=480:480, setsar=1[iv];[im][1:a][iv][1:a]concat=n=2:v=1:a=1[outv][outa]" -map "[outa]" -map "[outv]" output.mp4

// 图片生成视频
ffmpeg -f lavfi -t 10 -i anullsrc -loop 1 -framerate 10 -t 5 -i 1.jpg -vf "scale=664x478" -pix_fmt yuv420p output.mp4

// 添加第三条音频
 ffmpeg -i im.mp4 -i douyin.mp4 -i 1.mp3 -filter_complex "[0]scale=544x960,setsar=1[iv];[1]setsar=1[dv];[iv][0:a:0][dv][1:a:0]concat=n=2:v=1:a=1[ov][oa]" -map "[ov]" -map "[oa]" -map 2:a:0 -vsync 2 output.mp4

ffmpeg -i im.mp4 -i douyin.mp4 -i 1.mp3 -filter_complex "[0]scale=544x960,setsar=1[iv];[1]setsar=1[dv];[iv][0:a:0][dv][1:a:0]concat=n=2:v=1:a=1[ov][oa];[2:a:0][oa]amix=inputs=2:duration=first:dropout_transition=3[aa]" -map "[ov]" -map "[aa]" -vsync 2 output.mp4
ビデオのサムネイルを抽出する
// 三秒一张 fps=1/3 
ffmpeg -i input.mp4 -vf "fps=1/3, scale=128:72" output_%d.jpg
  >>> 音视频开发 视频教程: https://ke.qq.com/course/3202131?flowToken=1031864 
  >>> 音视频开发学习资料、教学视频,免费分享有需要的可以自行添加学习交流群 739729163 领取

おすすめ

転載: blog.csdn.net/weixin_52622200/article/details/131537307