使用“youtube-transcript”从 youtube 视频获取字幕

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

我试图使用 youtube-transcript 从 youtube 视频中获取字幕。它在单个 js 或 ts 文件中运行良好。但是当我在 Next JS 项目中使用它时,它就不起作用了。

下面是我的代码和我得到的错误。

import { YoutubeTranscript } from "youtube-transcript";
YoutubeTranscript.fetchTranscript("QY8dhl1EQfI").then(console.log);
Uncaught (in promise) Error: [YoutubeTranscript] 🚨 TypeError: URL is not a constructor
    at new YoutubeTranscriptError (youtube-transcript.esm.js:74:1)
    at Function.eval (youtube-transcript.esm.js:134:1)
    at step (youtube-transcript.esm.js:64:1)
    at Object.eval [as throw] (youtube-transcript.esm.js:45:46)
    at rejected (youtube-transcript.esm.js:36:42)

我在js文件中运行的预期结果

PS C:\Users\warren\Desktop\Training\tsnode> node test.js
[
  {
    text: 'what is going on everyone my name is',
    duration: 2800,
    offset: 399
  },
  {
    text: "anson and in this video i'm going to go",
    duration: 2960,
    offset: 1680
  },
  { text: 'ahead and teach you', duration: 2801, offset: 3199 },
  { text: 'how to', duration: 3440, offset: 4640 },
  { text: 'call the youtube data api', duration: 4400, offset: 6000 },
  {
    text: 'to get specific information from youtube',
    duration: 3599,
    offset: 8080
  },
  ...

有人可以向我解释一下我该怎么做才能避免错误吗?
感谢您的阅读。

youtube
1个回答
0
投票

此软件包不适用于客户端 Web (React CRA)。仅适用于后端。如果您需要在客户端应用程序中使用此包,您可能需要寻找与前端环境兼容的替代方案,或者考虑在后端实现您需要的功能并通过 API 将其公开给您的前端应用程序。 下面的代码是 Next JS App router


import { YoutubeTranscript } from 'youtube-transcript';

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const url = searchParams.get("url")!;
  try {
      const transcript = await YoutubeTranscript.fetchTranscript(url);
      return Response.json(transcript);
  }
  catch (error) {
      console.log(error);
      return Response.json({ error: 'Something went wrong' });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.