我正在使用npm-module中的库ytdl-core和ffmpeg for NodeJS我有两个函数,一个是下载视频,另一个是从Youtube视频中获取音频。这两个函数都是异步的,但在我的算法中,其中一个依赖于另一个。首先,我想要下载音频,在我想要获得音频源的视频之后,我不想同时异步执行这两个操作,我想要同步操作
这是我的代码:
var stream = app.ytdl(req.body.linkYoutube,{quality: 18});
//First, download audio
app.ffmpeg(stream)
.audioBitrate(128)
.save(`${__dirname}/music.mp3`)
.on('progress', (p) => {
app.readline.cursorTo(process.stdout, 0);
process.stdout.write(`${p.targetSize}kb downloaded`);
})
.on('end', () => {
res.status(200).download('./controllers/music.mp3');
});
//Second, download video of that audio
app.ytdl(req.body.linkYoutube, { filter : (format) =>
format.container === 'mp4' &&
format.qualityLabel ==='720p'// &&
// format.itag === 18
})
.pipe(app.fs.createWriteStream('video.mp4'));我知道这不好,但这是学习异步的一个很好的练习,谢谢!
发布于 2020-01-10 23:19:31
您可以使用Promise在第一个函数完成后立即执行第二个函数,如下所示:
new Promise(resolve => {
app.ffmpeg(stream)
.audioBitrate(128)
.save(`${__dirname}/music.mp3`)
.on('progress', (p) => {
app.readline.cursorTo(process.stdout, 0);
process.stdout.write(`${p.targetSize}kb downloaded`);
})
.on('end', () => {
res.status(200).download('./controllers/music.mp3');
resolve();
});
}).then(() => {
//Second, download video of that audio
app.ytdl(req.body.linkYoutube, {
filter: (format) =>
format.container === 'mp4' &&
format.qualityLabel === '720p'// &&
// format.itag === 18
})
.pipe(app.fs.createWriteStream('video.mp4'));
}
})https://stackoverflow.com/questions/59684212
复制相似问题