video_info_handler.dart 1.78 KB
import 'dart:io';

import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/utils/file_type_util.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:video_compress/video_compress.dart';

class VideoInfoHandler extends MessageHandler {
  @override
  Future handleMessage(params) async {
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }

    final url = params['url'] as String;

    String filePath;
    if (url.startsWith('http')) {
      // 获取后缀名
      String ext = path.extension(url);
      // 获取应用文档目录路径
      final Directory tempDir = await getApplicationDocumentsDirectory();

      final targetPath = path.join(tempDir.path, '${DateTime.now().millisecondsSinceEpoch}$ext');

      final resp = await Dio().download(url, targetPath);
      if (resp.statusCode != 200) {
        throw Exception('文件下载失败');
      }

      filePath = targetPath;
    } else {
      filePath = url;
    }

    final file = File(filePath);
    if (!file.existsSync()) {
      throw Exception('视频文件不存在');
    }

    // 使用video_compress获取视频信息
    final mediaInfo = await VideoCompress.getMediaInfo(filePath);

    // 获取文件大小
    final size = await file.length();

    // 获取MIME类型并转换为文件扩展名
    final mimeType = await FileTypeUtil.getMimeType(file);
    final fileExtension = FileTypeUtil.getExtensionFromMime(mimeType);

    return {
      'tempFilePath': '/temp$filePath',
      'width': mediaInfo.width ?? 0,
      'height': mediaInfo.height ?? 0,
      'type': fileExtension,
      'duration': (mediaInfo.duration ?? 0) / 1000, // 转换为秒
      'size': size,
    };
  }
}