video_util.dart 1.52 KB
import 'package:ffmpeg_kit_flutter_new/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_new/return_code.dart';

class VideoUtil {
  ///
  /// 将视频格式转换为mp4
  /// 转码的同时,进行压缩
  ///
  static Future<bool> convertToMp4(String inputPath, String outputPath) async {
    // final session = await FFmpegKit.execute(
    //     '-i "$inputPath" -c:v libx264 -c:a aac -strict experimental -movflags faststart -f mp4 "$outputPath"');
    final session = await FFmpegKit.execute(
        '-i "$inputPath" -c:v libx264 -crf 28 -c:a aac -b:a 128k -strict experimental -movflags faststart -f mp4 "$outputPath"');
    final returnCode = await session.getReturnCode();
    return ReturnCode.isSuccess(returnCode);
  }

  ///
  /// 通过 ffmpeg 压缩视频
  ///
  static Future<bool> compressVideo(String inputPath, String outputPath, String quality) async {
    // 使用CRF模式进行压缩,值范围0-51,建议值18-28
    // 高质量: CRF 18-20
    // 中等质量: CRF 23-26
    // 低质量: CRF 28-32
    int crf;
    switch (quality) {
      case 'low':
        crf = 32;
        break;
      case 'middle':
        crf = 26;
        break;
      case 'high':
        crf = 20;
        break;
      default:
        throw Exception('参数错误');
    }
    final session = await FFmpegKit.execute(
        '-i "$inputPath" -c:v libx264 -crf $crf -c:a aac -b:a 128k -preset medium -movflags faststart "$outputPath"');
    final returnCode = await session.getReturnCode();
    return ReturnCode.isSuccess(returnCode);
  }
}