compressVideo static method
- {required File video,
- required int maxFileSize,
- File? target,
- VideoQuality? quality}
Compresses video
This method compresses the video at-least once and then keeps it compressing until Compression.maxFileSize is reached.
See also
Implementation
static Future<File?> compressVideo({
required File video,
required int maxFileSize,
File? target,
VideoQuality? quality,
}) async {
try {
quality ??= VideoQuality.Res640x480Quality;
File compressedVideo = video;
final int originalSize = await compressedVideo.length();
int iteration = 1;
if (kDebugMode) print('Size before compression : $originalSize');
int compressedSize;
do {
final MediaInfo? info = await VideoCompress.compressVideo(
compressedVideo.path,
quality: quality,
includeAudio: true,
frameRate: 24,
);
if (info == null || info.file == null) throw PlatformException(code: 'PROCESS_ERR');
compressedVideo = info.file!;
compressedSize = await compressedVideo.length();
if (compressedSize > originalSize) throw PlatformException(code: 'COMPRESS_ERR');
if (kDebugMode) print('Size after compression $iteration : $compressedSize');
++iteration;
} while (compressedSize >= maxFileSize && iteration < 4);
/// Create target file
File? newTarget = target;
if (newTarget == null) {
final String fileExtension = path.extension(compressedVideo.absolute.path).toLowerCase();
final String newName = 'VID_${DateTime.now().microsecondsSinceEpoch}$fileExtension';
final String dir = path.dirname(compressedVideo.absolute.path);
newTarget = File(path.join(dir, newName));
}
/// Delete target if exists
if (newTarget.existsSync()) await newTarget.delete();
/// move file to target
final File compressed = await compressedVideo.copy(newTarget.absolute.path);
/// Delete cached file
if (compressedVideo.absolute.path != compressed.absolute.path) await compressedVideo.delete();
return compressed;
} catch (e) {
if (kDebugMode) print(e);
rethrow;
}
}