youtube_explode/example/video_download.dart

88 lines
2.3 KiB
Dart
Raw Normal View History

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();
// Get the video url.
var id = YoutubeExplode.parseVideoId(url);
if (id == null) {
console.writeLine('Invalid video id or url.');
exit(1);
}
// Save the video to the download directory.
Directory('downloads').createSync();
console.hideCursor();
// Download the video.
await download(id);
yt.close();
console.showCursor();
exit(0);
}
Future<void> download(String id) async {
// Get the video media stream.
var mediaStream = await yt.getVideoMediaStream(id);
// Get the last audio track (the one with the highest bitrate).
var audio = mediaStream.audio.last;
// Compose the file name removing the unallowed characters in windows.
var fileName =
'${mediaStream.videoDetails.title}.${audio.container.toString()}'
.replaceAll('Container.', '')
.replaceAll(r'\', '')
.replaceAll('/', '')
.replaceAll('*', '')
.replaceAll('?', '')
.replaceAll('"', '')
.replaceAll('<', '')
.replaceAll('>', '')
.replaceAll('|', '');
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-03-06 23:18:33 +01:00
var len = audio.size;
2020-02-20 19:50:10 +01:00
var count = 0;
var oldProgress = -1;
// Create the message and set the cursor position.
var msg = 'Downloading `${mediaStream.videoDetails.title}`: \n';
var row = console.cursorPosition.row;
var col = msg.length - 2;
console.cursorPosition = Coordinate(row, 0);
console.write(msg);
// Listen for data received.
2020-03-06 23:18:33 +01:00
await for (var data in audio.downloadStream()) {
2020-02-20 19:50:10 +01:00
count += data.length;
var progress = ((count / len) * 100).round();
if (progress != oldProgress) {
console.cursorPosition = Coordinate(row, col);
console.write('$progress%');
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
}