我正在尝试从 youtube 数据 api 下载字幕,但遇到错误

问题描述 投票:0回答:1

我在 node.js 服务器中使用 googleapi 从给定视频 ID 的 YouTube 视频中提取字幕。我已经在谷歌云中启用了youtube数据api,使用了正确的clientID和客户端密钥。

它抛出此错误:错误:未设置访问权限、刷新令牌、API 密钥或刷新处理程序回调。对于这段代码:

 const captionsResponse = await youtube.captions.list({
      part: "snippet",
      videoId: videoId,
    });

这是我的完整代码:

const express = require("express");
const { google } = require("googleapis");
const { OAuth2 } = google.auth;

const router = express.Router();

const clientId =process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const redirectUri = process.env.REDIRECT-URI;
const oauth2Client = new OAuth2(clientId, clientSecret, redirectUri);

// Set up YouTube API client
const youtube = google.youtube({
  version: "v3",
  auth: oauth2Client,
});

router.get("/:videoId", async (req, res) => {
  try {
    const { videoId } = req.params;

    
    // Call the captions.list method to get the captions for the specified video
    const captionsResponse = await youtube.captions.list({
      part: "snippet",
      videoId: videoId,
    });
    if (captionsResponse.data.items.length === 0) {
      res.status(400).json({
        success: false,
        message: "This video doesn't have a transcript!",
      });
      return;
    }

    // Get the ID of the first caption
    const captionId = captionsResponse.data.items[0].id;

    // Call the captions.download method to get the transcript text
    const transcriptResponse = await youtube.captions.download({
      id: captionId,
      tfmt: "vtt", // Specify the format of the transcript (e.g., WebVTT)
    });

    const transcriptText = transcriptResponse.data;

    res.status(200).json({ success: true, transcript: transcriptText });
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ success: false, message: "Failed to retrieve transcript" });
  }
});



module.exports = router;

我期望得到的是文字记录

javascript node.js google-cloud-platform google-api youtube-data-api
1个回答
0
投票

我正在尝试做几乎相同的事情,您的 API 调用缺少访问令牌,请尝试在查询参数中添加 yout api 密钥。但这个特定端点需要 O2Auth 令牌。

我尝试使用其 ID 获取现有标题,但收到 404 错误。

控制台记录您的访问令牌以验证它是否存在且未过期。

© www.soinside.com 2019 - 2024. All rights reserved.