flutter实行Asset中的可实行文件

[复制链接]
发表于 2026-1-27 23:42:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一、配景

之前做一个音视频合成的工具类,须要将ffmpeg打包进Asset中,但是没有很好的办法运行Asset中的ffmpeg。
二、实现

思绪:获取体系暂时目次,将ffmpeg从Asset中读取,然后写入到体系暂时目次中再使用。
  1. import 'dart:io';
  2. import 'package:flutter/services.dart';
  3. class FFmpegUtil {
  4.   static final ffmpegExeFileName = Platform.isWindows ? 'ffmpeg.exe' : 'ffmpeg';
  5.   static String? _ffmpegPath;
  6.   static Future<void> init() async {
  7.     final documentsDir = Directory.systemTemp;
  8.     final ffmpegFile = File('${documentsDir.path}/$ffmpegExeFileName');
  9.     final ffmpegBytes =
  10.         await rootBundle.load('assets/ffmpeg/$ffmpegExeFileName');
  11.     if (ffmpegFile.existsSync() &&
  12.         ffmpegFile.lengthSync() == ffmpegBytes.buffer.lengthInBytes) {
  13.       print('Will use existed ffmpeg file: $ffmpegFile');
  14.       _ffmpegPath = ffmpegFile.path;
  15.       return;
  16.     }
  17.     print('Will copy to ffmpeg file: $ffmpegFile');
  18.     // 将 FFmpeg 可执行文件写入应用程序的文档目录
  19.     await ffmpegFile.writeAsBytes(ffmpegBytes.buffer.asUint8List());
  20.     // 设置文件权限为可执行
  21.     if (Platform.isMacOS) {
  22.       await Process.run('chmod', ['+x', ffmpegFile.path]);
  23.     }
  24.     _ffmpegPath = ffmpegFile.path;
  25.   }
  26. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表