我必须从网站下载媒体文件,该网站返回的视频网址如下:
我使用flutter_downlaoder下载了此视频文件。
下载的文件不包含任何扩展名,因此我必须自己添加它。
我必须以以下格式重命名下载的文件:
[用户名] _ [时间戳] .mp4
问题是,当我下载此无扩展名的视频文件并通过从存储目录重命名手动添加它时,视频可以正常播放,但是当我以编程方式重命名时,它无法播放并显示“视频格式错误”。
我在下面分享了我的代码。如何解决此问题?
Future downloadMedia(String userName, String videoURL, String downloadPath, BuildContext context) async {
String filename = "${userName}_${DateTime.now().millisecondsSinceEpoch}";
String downloadURL = videoURL;
String taskId = await FlutterDownloader.enqueue(
url: downloadURL,
savedDir: downloadPath,
fileName: filename,
showNotification: false,
openFileFromNotification: false);
FlutterDownloader.registerCallback((id, status, progress) async {
if (progress.toInt() >= 100) {
String newFilename = "$filename.mp4";
Future.delayed(const Duration(milliseconds: 500), () {
File(downloadPath + "/" + filename)
.renameSync(downloadPath + "/" + newFilename);
});
}
});
}
答案 0 :(得分:0)
我四处搜索,发现重命名视频文件总是会弄乱视频编解码器设置,因此最好的方法是使用FFMpeg处理它。
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';
class Download {
final FlutterFFmpeg _flutterFFmpeg = FlutterFFmpeg();
Future downloadMedia(String userName, String videoURL, String downloadPath,
BuildContext context) async {
String filename = "${userName}_${DateTime.now().millisecondsSinceEpoch}";
String filenameOriginal =
"${userName}_${DateTime.now().millisecondsSinceEpoch}";
String downloadURL = videoURL;
var started = false;
await FlutterDownloader.enqueue(
url: downloadURL,
savedDir: downloadPath,
fileName: filename,
showNotification: false,
openFileFromNotification: false);
FlutterDownloader.registerCallback((id, status, progress) async {
if (progress.toInt() >= 100) {
started = true;
var inputFile = "${downloadPath + "/" + filename}";
var outputFile = "${downloadPath + "/" + filenameOriginal}_${DateTime.now().millisecondsSinceEpoch}.mp4";
_flutterFFmpeg
.execute("-i inputFile -c copy outputFile")
.then((rc) => print("FFmpeg process exited with rc $rc"));
//Export file as Mp4 Video
}
});
}
}
导出的视频文件可以在VLC播放器或MX播放器应用中轻松播放。