video_util.dart 2.03 KB
import 'dart:io';

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 {

    String cmd;
    if(Platform.isIOS) {
      // 构建命令
      // 1. -c:v h264_videotoolbox : 启用 iOS 硬件加速
      // 2. -b:v 1500k             : 限制视频码率为 1.5Mbps (体积小,手机看足够)
      // 3. -vf scale=1280:-2      : 缩放到 720p (保持比例)
      // 4. -c:a aac               : 音频转为 AAC (兼容性最好)
      // 5. -b:a 128k              : 音频码率
      cmd =
          '-i "$inputPath" '
          '-c:v h264_videotoolbox -b:v 1500k '
          '-vf scale=1280:-2 '
          '-c:a aac -b:a 128k '
          '"$outputPath"';

      print("开始极速转码: $cmd");
    } else {
      cmd = '-i "$inputPath" -c:v libx264 -crf 28 -c:a aac -b:a 128k -strict experimental -movflags faststart -f mp4 "$outputPath"';
    }
    final session = await FFmpegKit.execute(cmd);
    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);
  }
}