You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中使用ffmpeg_kit_flutter合并资源文件与录制视频

解决视频顺序合并与Assets路径问题

一、解决Assets文件无法访问的问题

FFmpeg无法直接读取项目Assets目录下的资源,必须先将Assets中的视频复制到设备本地可访问的文件路径(如临时目录或应用私有目录)。具体实现:

  1. 添加依赖:需要path_provider包用于获取本地目录,以及flutter/services.dart用于读取Assets资源
  2. 编写复制Assets到本地的函数
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

Future<String> copyAssetToLocal(String assetPath) async {
  // 获取设备临时目录
  final tempDir = await getTemporaryDirectory();
  final localFile = File('${tempDir.path}/intro.mp4');

  // 避免重复复制,文件已存在直接返回路径
  if (await localFile.exists()) {
    return localFile.path;
  }

  // 读取Assets文件并写入本地
  final byteData = await rootBundle.load(assetPath);
  await localFile.writeAsBytes(byteData.buffer.asUint8List());

  return localFile.path;
}

二、修正FFmpeg顺序合并命令

你之前使用hstack滤镜导致视频左右并列,换成concat滤镜是正确的方向,同时要确保命令参数和输入顺序正确:

Future<void> mergeRecordWithIntro(String outputPath, String recordedVideoPath) async {
  emit(MergeVideoLoading());
  
  // 1. 将Assets中的intro.mp4复制到本地可访问路径
  final String introLocalPath = await copyAssetToLocal('assets/intro.mp4');

  // 2. 构建正确的顺序拼接命令
  final String filter = '[0:v]scale=480:640,setsar=1[v0];[1:v]scale=480:640,setsar=1[v1];[v0][0:a][v1][1:a]concat=n=2:v=1:a=1[outv][outa]';
  final String command = '-y -i $introLocalPath -i $recordedVideoPath -filter_complex "$filter" -map "[outv]" -map "[outa]" $outputPath';

  await FFmpegKit.execute(command).then((value) async {
    final returnCode = await value.getReturnCode();

    if (ReturnCode.isSuccess(returnCode)) {
      await GallerySaver.saveVideo(outputPath);
      emit(MergeVideoSuccess());
    } else if (ReturnCode.isCancel(returnCode)) {
      emit(MergeVideoError());
    } else {
      // 打印错误日志辅助排查
      final logs = await value.getAllLogs();
      print('FFmpeg错误日志: ${logs.map((log) => log.getMessage()).join('\n')}');
      emit(MergeVideoError());
    }
  });
}

关键说明

  • 路径逻辑:Assets资源是打包在App内部的,FFmpeg只能访问设备文件系统路径,因此必须先复制到本地
  • 合并逻辑:concat=n=2:v=1:a=1表示拼接2个输入源,输出1路视频和1路音频;输入顺序introLocalPath在前、录制视频路径在后,确保视频按intro→录制内容的顺序播放
  • 错误排查:如果合并失败,打印FFmpeg日志可以快速定位问题(比如视频编码不兼容、分辨率参数错误等)

内容的提问来源于stack exchange,提问作者Abderrahman Belhadj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:43:09