I am using this dependency https://github.com/fent/node-ytdl-core, on my provisionService :
getStream(url: string): Observable<any> {
const stream = ytdl(url);
return new Observable((obs: NextObserver<any>) => {
stream.on('progress', (length, downloaded, totalLength) => {
console.log({length, downloaded, totalLength});
});
stream.on('finish', () => {
console.log('stream has FINISHED');
obs.next(stream);
obs.complete();
});
});
}
that it's been called from my component
downloadYoutubeVideo(youTubeId: string) {
const observable$ = this.provisionService.getStream(youTubeId);
const observer = {
next: (stream) => { xxx }
};
observable$.subscribe(observer);
}
So I can download some short videos. But if I try to download longer ones, then progress will be incomplete, logging only the previous progress not reaching where the downloaded is the same as totalLength. So the stream never finishes. Any idea how to fix it and why it happens?
Cheers
You are passing an already "finished" stream, why dont you pass the stream directly as a response from getStreamWithInfo
function?
getStreamWithInfo(url: string): Observable<any> {
console.log('getting stream observable');
return new Observable((observer: NextObserver<any>) => {
// const url = 'https://www.youtube.com/watch?v=' + location;
ytdl.getInfo(url).then(
info => {
console.log(info.formats);
const formats = ytdl.filterFormats(info.formats, 'audioandvideo');
if (formats.length < 1) {
console.log('no formats retrieved');
observer.error('Video formats not available');
return;
} else {
// this.stopRetry = true;
}
console.log(formats);
const downloadOptions = {
quality: 'highest',
format: formats[0]
};
const stream = ytdl.downloadFromInfo(info, downloadOptions);
observer.next(stream); //Here you pass the stream directly
}
,
error => {
console.error(error);
alert('Video info not available:');
console.log('stream has ERRORED', error.toString());
observer.error(error);
throw new Error('Video info not available');
}
);
});
}