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

YouTube Data API V3字幕获取异常:调用captions.list未得到字幕内容

解决YouTube Data API获取实际字幕内容的问题

你当前调用的captions.list接口仅用于获取字幕的元数据(比如ID、语言、类型等),要拿到实际的字幕文本,需要使用**captions.download接口**,结合从captions.list返回的字幕ID来请求。以下是完整的解决方案:


核心步骤

  1. 通过captions.list获取目标字幕的ID(优先选择人工生成的standard类型字幕,比自动转录的asr准确率更高)
  2. 使用captions.download接口,传入字幕ID和指定的输出格式,获取原始字幕内容
  3. 解析返回的字幕格式(如TTML/SRT/VTT)提取纯文本

完整代码示例

async function getCaptionByVideoId(id) {
  try {
    // 1. 获取字幕元数据,筛选目标字幕ID
    const listResponse = await gapi.client.youtube.captions.list({
      part: ["snippet"],
      videoId: id,
      tlang: 'en'
    });

    if (!listResponse.result?.items?.length) {
      console.log("未找到可用的英文字幕");
      return null;
    }

    // 优先选择人工制作的standard字幕,无则选第一个结果
    const targetCaption = listResponse.result.items.find(item => item.snippet.trackKind === 'standard') 
                          || listResponse.result.items[0];

    // 2. 调用download接口获取实际字幕内容
    const downloadResponse = await gapi.client.youtube.captions.download({
      id: targetCaption.id,
      tfmt: 'srt', // 可选格式:ttml/srt/vtt,srt更易解析
      tlang: 'en'
    });

    // 3. 解析SRT格式的字幕(如果选ttml/vtt,需对应修改解析逻辑)
    const srtContent = downloadResponse.body;
    const subtitles = srtContent.split(/\n\n/)
      .filter(block => block.trim())
      .map(block => {
        // 去掉序号和时间轴,只保留文本
        const lines = block.split('\n');
        return lines.slice(2).join(' ').trim();
      })
      .filter(text => text);

    return subtitles;
  } catch (error) {
    console.error("获取字幕失败:", error);
  }
}

关键注意事项

  • 权限配置:确保你的OAuth 2.0请求包含正确的权限范围:
    • 公开视频字幕:使用https://www.googleapis.com/auth/youtube.readonly
    • 私有/受限视频字幕:需使用更高权限(如https://www.googleapis.com/auth/youtube)
  • 格式选择:tfmt参数推荐选srt或vtt,这两种格式比TTML更易解析;如果坚持用TTML,可通过DOMParser解析XML提取<text>标签内容
  • 配额限制:YouTube Data API有调用配额限制,注意控制请求频率,避免触发限流

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:01:28