我正在制作一个Flutter视频下载管理器。我正在使用flutter_downloader插件。但所面临的问题是,要么视频不下载,要么下载后不播放。下面是从Facebook和Instagram下载视频的代码。
Future<void> _startDownload() async {
final url = _urlController.text.trim();
if (url.isEmpty) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Empty URL'),
content: const Text('Please enter a video URL.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
return;
} else if (!isValidVideoUrl(url)) {
// Show an error message or handle the invalid URL case
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Invalid URL'),
content: const Text('Please enter a valid video URL.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
return;
} else {
TaskInfo task = TaskInfo(url: url);
await _requestDownload(task);
setState(() {
_tasks!.add(task);
_items!.add(ItemHolder(name: task.name, task: task));
});
}
}
bool isValidVideoUrl(String url) {
final Uri? uri = Uri.tryParse(url);
if (uri == null) {
// Invalid URL format
return false;
}
// Check if the URL scheme is HTTP or HTTPS
if (uri.scheme != 'http' && uri.scheme != 'https') {
return false;
}
// Check if the URL host belongs to a valid video hosting platform
final String host = uri.host.toLowerCase();
if (host.contains('www.instagram.com') ||
host.contains('www.tiktok.com') ||
host.contains('www.reels.com') ||
host.contains('www.facebook.com')) {
return true;
}
//Invalid video URL
return false;
}
解析URI
Future<void> _requestDownload(TaskInfo task) async {
final url = task.url!;
if (_permissionReady) {
final fileName = '${DateTime.now().millisecondsSinceEpoch}.mp4';
final response = await Dio().head(url);
final contentType = response.headers['content-type']?.toString();
final fileExtension = _getFileExtension(contentType);
task.taskId = await FlutterDownloader.enqueue(
url: url,
savedDir: _localPath!,
fileName: '$fileName$fileExtension',
saveInPublicStorage: _saveInPublicStorage,
showNotification: true,
openFileFromNotification: true,
);
}
}
String _getFileExtension(String? contentType) {
if (contentType != null) {
if (contentType.contains('video/mp4')) {
return '.mp4';
} else if (contentType.contains('video/3gpp')) {
return '.3gp';
} else if (contentType.contains('video/mpeg')) {
return '.mpg';
}
// Add more cases for other content types and their corresponding file extensions
}
return '.mp4'; // Default to '.mp4' if the content type is unknown
}
我想以正确的格式下载文件,下载后必须播放视频。
1条答案
按热度按时间piok6c0g1#
你不能通过分享URL从FB或Instagram下载视频,你必须获得一个真实的的下载路径