- 检查视频信息:在尝试下载之前,首先查询视频的信息,了解可用的格式。这可以通过 ytdl-core 的
getInfo
方法实现。
const ytdl = require('@ybd-project/ytdl-core');
async function getVideoInfo(videoUrl) {
try {
const info = await ytdl.getInfo(videoUrl);
console.log(info.formats); // 打印出所有可用的格式
return info;
} catch (error) {
console.error('Error getting video info:', error);
}
}
- 选择合适的格式:根据查询到的视频信息,选择一个确实存在的格式进行下载。
async function downloadVideo(videoUrl, format) {
const info = await getVideoInfo(videoUrl);
const formatId = info.formats.find(f => f.qualityLabel === format).itag;
const stream = ytdl(videoUrl, { format: formatId });
stream.pipe(fs.createWriteStream(`output_${format}.mp4`));
}
- 错误处理:使用
try
和 catch
语句捕获下载过程中可能出现的错误,并进行相应的处理。
async function safeDownloadVideo(videoUrl, format) {
try {
await downloadVideo(videoUrl, format);
console.log('Download successful');
} catch (error) {
console.error('Download failed:', error);
}
}
- 循环尝试:如果下载失败,可以设置一个循环,尝试多次下载,直到成功为止。
async function retryDownload(videoUrl, format, maxAttempts = 5) {
let attempts = 0;
while (attempts < maxAttempts) {
try {
await safeDownloadVideo(videoUrl, format);
break;
} catch (error) {
console.log(`Attempt ${attempts + 1} failed`);
attempts++;
}
}
}