You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

youtube-dl-exec无法获取可读流且安装youtube-dl报错如何解决

问题解决方案

一、无需更换库,直接用youtube-dl-exec获取可读流

你当前返回JSON结构是因为开启了dumpSingleJson: true参数,要获取可读流有两种实现方式:

方式1:直接获取输出流(不需要先拉元数据)

去掉dumpSingleJson参数,配置输出到标准输出,直接获取子进程的stdout作为可读流:

const youtubedl = require('youtube-dl-exec').raw;
// 直接创建子进程获取流
const stream = youtubedl(url, [
  '--no-warnings',
  '--audio-format', 'mp3',
  '--no-check-certificate',
  '--prefer-free-formats',
  '--youtube-skip-dash-manifest',
  '--referer', 'https://google.com',
  '-o', '-' // 输出到标准输出
]).stdout;
// 直接传入创建音频资源
const resource = createAudioResource(stream);

方式2:先拿元数据再请求流

如果你需要先获取视频标题、时长等元数据,再拉取音频流,只需要在请求你拿到的googlevideo地址时,带上对应请求头即可,之前地址不可用是因为Google校验请求的Referer字段:

// 先过滤出可用的音频流,不要直接取formats[0],可能是无音频的视频流
const audioFormat = output.formats.find(item => item.acodec !== 'none' && item.ext === 'mp3');
if (!audioFormat) throw new Error('未找到可用音频流');
// 发起请求时带上Referer头
const https = require('https');
https.get(audioFormat.url, {
  headers: {
    'Referer': 'https://google.com'
  }
}, (res) => {
  // res即为可读流
  const resource = createAudioResource(res);
}).on('error', err => console.error('拉取音频流失败:', err));

二、修复youtube-dl包安装报错

该报错是因为旧版youtube-dl@3.5.0依赖的版本校验工具不兼容新版Node.js环境,且该包已停止维护,不推荐使用,如果必须安装可以跳过安装脚本:

npm install youtube-dl --ignore-scripts

安装完成后需要手动下载youtube-dl/yt-dlp二进制文件,并将其路径配置到系统环境变量中,否则调用时会报错。

内容的提问来源于stack exchange,提问作者C3010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:06:01