youtube_explode/example/video_download.dart

88 lines
2.3 KiB
Dart
Raw Normal View History

2020-06-05 20:18:42 +02:00
//TODO: Fixing the console printing.
2020-02-20 19:50:10 +01:00
import 'dart:async';
import 'dart:io';
import 'package:dart_console/dart_console.dart';
2020-02-20 19:55:45 +01:00
import 'package:youtube_explode_dart/youtube_explode_dart.dart';
2020-02-20 19:50:10 +01:00
// Initialize the YoutubeExplode instance.
final yt = YoutubeExplode();
final console = Console();
Future<void> main() async {
console.writeLine('Type the video id or url: ');
2020-03-06 23:18:33 +01:00
2020-02-20 19:50:10 +01:00
var url = stdin.readLineSync().trim();
// Save the video to the download directory.
Directory('downloads').createSync();
console.hideCursor();
// Download the video.
2020-06-05 20:08:04 +02:00
await download(url);
2020-02-20 19:50:10 +01:00
yt.close();
console.showCursor();
exit(0);
}
Future<void> download(String id) async {
2020-06-05 20:08:04 +02:00
// Get video metadata.
var video = await yt.videos.get(id);
// Get the video manifest.
var manifest = await yt.videos.streamsClient.getManifest(id);
2020-06-05 20:14:22 +02:00
var streams = manifest.audioOnly;
2020-02-20 19:50:10 +01:00
// Get the last audio track (the one with the highest bitrate).
2020-06-05 20:08:04 +02:00
var audio = streams.last;
var audioStream = yt.videos.streamsClient.get(audio);
2020-02-20 19:50:10 +01:00
// Compose the file name removing the unallowed characters in windows.
2020-06-05 20:08:04 +02:00
var fileName = '${video.title}.${audio.container.name.toString()}'
.replaceAll('Container.', '')
.replaceAll(r'\', '')
.replaceAll('/', '')
.replaceAll('*', '')
.replaceAll('?', '')
.replaceAll('"', '')
.replaceAll('<', '')
.replaceAll('>', '')
.replaceAll('|', '');
2020-02-20 19:50:10 +01:00
var file = File('downloads/$fileName');
// Create the StreamedRequest to track the download status.
// Open the file in appendMode.
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
// Track the file download status.
2020-06-05 20:08:04 +02:00
var len = audio.size.totalBytes;
2020-02-20 19:50:10 +01:00
var count = 0;
var oldProgress = -1;
// Create the message and set the cursor position.
2020-06-05 20:08:04 +02:00
var msg = 'Downloading `${video.title}`(.${audio.container.name}): \n';
print(msg);
// var row = console.cursorPosition.row;
// var col = msg.length - 2;
// console.cursorPosition = Coordinate(row, 0);
// console.write(msg);
2020-02-20 19:50:10 +01:00
// Listen for data received.
2020-06-05 20:08:04 +02:00
await for (var data in audioStream) {
2020-02-20 19:50:10 +01:00
count += data.length;
var progress = ((count / len) * 100).round();
if (progress != oldProgress) {
2020-06-05 20:08:04 +02:00
// console.cursorPosition = Coordinate(row, col);
print('$progress%');
2020-02-20 19:50:10 +01:00
oldProgress = progress;
}
output.add(data);
2020-03-06 23:18:33 +01:00
}
console.writeLine();
await output.close();
2020-02-20 19:50:10 +01:00
}