12ytdl 中文文档教程

发布于 3年前 浏览 34 项目主页 更新于 3年前

node-ytdl-core

Depfu codecovDiscord

另一个 YouTube下载模块。 仅使用 Javascript 和节点友好的流媒体界面编写。

Support

您可以在我们的聊天服务器 上联系我们以获取支持

Usage

const fs = require('fs');
const ytdl = require('ytdl-core');
// TypeScript: import ytdl from 'ytdl-core'; with --esModuleInterop
// TypeScript: import * as ytdl from 'ytdl-core'; with --allowSyntheticDefaultImports
// TypeScript: import ytdl = require('ytdl-core'); with neither of the above

ytdl('http://www.youtube.com/watch?v=aqz-KE-bpKQ')
  .pipe(fs.createWriteStream('video.mp4'));

API

ytdl(url, [options])

尝试从给定的 url 下载视频。 返回一个可读流。 除了任何 getInfo() 选项chooseFormat() 选项

  • range - A byte range in the form {start: INT, end: INT} that specifies part of the file to download, ie {start: 10355705, end: 12452856}. Not supported on segmented (DASH MPD, m3u8) formats.
  • This downloads a portion of the file, and not a separately spliced video.
  • begin - What time in the video to begin. Supports formats 00:00:00.000, 0ms, 0s, 0m, 0h, or number of milliseconds. Example: 1:30, 05:10.123, 10m30s.
  • For live videos, this also accepts a unix timestamp or Date object, and defaults to Date.now().
  • This option is not very reliable for non-live videos, see #129 and #219.
  • liveBuffer - How much time buffer to use for live videos in milliseconds. Default is 20000.
  • highWaterMark - How much of the video download to buffer into memory. See node's docs for more. Defaults to 512KB.
  • dlChunkSize - When the chosen format is video only or audio only, the download is separated into multiple chunks to avoid throttling. This option specifies the size of each chunk in bytes. Setting it to 0 disables chunking. Defaults to 10MB.

Event: info

在获取视频的 info 以及选择的下载格式时发出。

Event: progress

  • number - Chunk length in bytes or segment number.
  • number - Total bytes or segments downloaded.
  • number - Total bytes or segments.

每当收到新块时发出。 传递描述下载进度的值。

miniget events

所有 miniget 事件 都被转发,并且可以从返回的流中收听。

Stream#destroy()

调用以中止并停止下载视频。

async ytdl.getBasicInfo(url, [options])

如果您只想从视频中获取元信息,请使用此选项。

async ytdl.getInfo(url, [options])

从视频中获取元信息。 包括额外的格式,以及准备下载解密的 URL。 这就是 ytdl() 函数内部使用的内容。

options 可以有以下内容

  • requestOptions - Anything to merge into the request options which miniget is called with, such as headers.
  • requestCallback - Provide a callback function that receives miniget request stream objects used while fetching metainfo.
  • lang - The 2 character symbol of a language. Default is en.

ytdl.downloadFromInfo(info, options)

一旦您使用 ytdl.getInfo 函数从视频中接收到元数据,您可以将该信息与其他选项一起传递给该函数。

ytdl.chooseFormat(formats, options)

如果您想自己选择一种格式,则可以使用。 如果找不到任何匹配的格式,则抛出错误。

options 可以有以下

  • quality - 下载的视频质量。 可以是 itag 值、itag 值列表或以下字符串之一:highest/lowest/highestaudio/lowestaudio/highestvideo/lowestvideo. highestaudio/lowestaudio 尝试最小化同样好的音频格式的视频比特率,而 highestvideo/lowestvideo 分别尝试最小化音频. 默认为 highest,它更喜欢同时具有视频和音频的格式。

    典型的视频格式将使用 quality: 'highest' 按以下方式排序

  itag container quality codecs                 bitrate  audio bitrate
  18   mp4       360p    avc1.42001E, mp4a.40.2 696.66KB 96KB
  137  mp4       1080p   avc1.640028            4.53MB
  248  webm      1080p   vp9                    2.52MB
  136  mp4       720p    avc1.4d4016            2.2MB
  247  webm      720p    vp9                    1.44MB
  135  mp4       480p    avc1.4d4014            1.1MB
  134  mp4       360p    avc1.4d401e            593.26KB
  140  mp4               mp4a.40.2                       128KB

360p 的格式 18 将被首先选择,因为它是视频和音频的最高质量格式。 如果您想要更高质量的视频和音频格式,请参阅处理单独的流部分。

  • filter - Used to filter the list of formats to choose from. Can be audioandvideo or videoandaudio to filter formats that contain both video and audio, video to filter for formats that contain video, or videoonly for formats that contain video and no additional audio track. Can also be audio or audioonly. You can give a filtering function that gets called with each format available. This function is given the format object as its first argument, and should return true if the format is preferable.
  // Example with custom function.
  ytdl(url, { filter: format => format.container === 'mp4' })
  • format - Primarily used to download specific video or audio streams. This can be a specific format object returned from getInfo.
  • Supplying this option will ignore the filter and quality options since the format is explicitly provided.
// Example of choosing a video format.
let info = await ytdl.getInfo(videoID);
let format = ytdl.chooseFormat(info.formats, { quality: '134' });
console.log('Format found!', format);

ytdl.filterFormats(formats, filter)

如果您只想处理某些格式,可以使用上面的filter 选项

// Example of filtering the formats to audio only.
let info = await ytdl.getInfo(videoID);
let audioFormats = ytdl.filterFormats(info.formats, 'audioonly');
console.log('Formats with only audio: ' + audioFormats.length);

ytdl.validateID(id)

如果给定的字符串满足 YouTube 的 ID 格式,则返回 true。

ytdl.validateURL(url)

如果能够解析出有效的视频 ID,则返回 true。

ytdl.getURLVideoID(url)

从 YouTube 网址返回视频 ID。 如果无法解析 ID,则抛出错误。

ytdl.getVideoID(str)

与上面的 ytdl.getURLVideoID() 相同,但可以直接使用视频 ID 调用,在这种情况下它会返回它。 这是 ytdl 内部使用的。 如果无法解析 ID,则抛出错误。

ytdl.version

直接从 package.json 中获取的版本字符串。

Limitations

ytdl 无法下载属于以下内容的视频

  • Regionally restricted (requires a proxy)
  • Private (if you have access, requires cookies)
  • Rentals (if you have access, requires cookies)
  • YouTube Premium content (if you have access, requires cookies)
  • Only HLS Livestreams are currently supported. Other formats will get filtered out in ytdl.chooseFormats

生成的下载链接有效期为 6 小时,并且只能从同一 IP 地址下载。

Handling Separate Streams

通常 1080p 或更好的视频没有用它编码的音频。 音频必须单独下载并通过编码库合并。 ffmpeg 是使用最广泛的工具,有许多 可用的 Node.js 模块。 使用从 ytdl.getInfo 返回的 format 对象下载特定流以组合以满足您的需要。 查看 example/ffmpeg.js 以获取执行此操作的示例。

What if it stops working?

YouTube 一直在更新他们的网站,停止工作的情况并不少见。 如果它对您不起作用并且您使用的是最新版本,请随时提出问题。 确保检查是否没有出现相同错误的人。

test/irl-test.js 运行测试以确保这确实是 ytdl-core 的问题。

npm run test:irl

这些测试没有被嘲笑,他们尝试开始下载一些视频。 如果这些都失败了,那么就该调试了。 如果您收到的错误是签名解密,请检查 lib/sig.js。 否则,错误可能在 lib/info.js 中。

Install

npm install ytdl-core@latest

或者对于 Yarn 用户:

yarn add ytdl-core@latest

确保您正在安装最新版本的 ytdl-core 以跟上最新的修复。

如果您使用的是使用 ytdl-core 的机器人或应用,例如 ytdl-core-discorddiscord-player,它可能依赖于旧版本。 要更新其 ytdl-core 版本,该库必须更新其 package.json 文件,您不能简单地更改项目的 package.json 上的版本,应用程序仍将使用自己的旧版本 ytdl-core。

查看他们的回购协议,看看他们是否已经有更新 ytdl-core 的活动拉取请求。 如果他们不这样做,请打开一个问题,要求他们更新 ytdl-core,或者更好的是,分叉该项目并提交包含更新版本的拉取请求。

当您等待拉取请求合并时,您可以在 package.json 中指向它的分支

  "ytdl-core-discord": "amishshah/ytdl-core-discord#dependabot/npm_and_yarn/ytdl-core-2.0.1"

Update Checks

使用过时版本的 ytdl-core 的问题变得如此普遍,ytdl-core 现在检查在运行时更新,每 12 小时更新一次。 如果找到更新,它会向控制台打印一条警告,建议您进行更新。 由于此库的性质,在 YouTube 持续更新时始终使用最新版本非常重要。

如果您想禁用此更新检查,您可以通过提供 YTDL_NO_UPDATE 环境变量来实现。

env YTDL_NO_UPDATE=1 node myapp.js

Related Projects

  • ytdl - A cli wrapper of this.
  • pully - Another cli wrapper of this aimed at high quality formats.
  • ytsr - YouTube video search results.
  • ytpl - YouTube playlist and channel resolver.

Tests

测试是用 mocha 编写的

npm test

node-ytdl-core

Depfu codecovDiscord

Yet another YouTube downloading module. Written with only Javascript and a node-friendly streaming interface.

Support

You can contact us for support on our chat server

Usage

const fs = require('fs');
const ytdl = require('ytdl-core');
// TypeScript: import ytdl from 'ytdl-core'; with --esModuleInterop
// TypeScript: import * as ytdl from 'ytdl-core'; with --allowSyntheticDefaultImports
// TypeScript: import ytdl = require('ytdl-core'); with neither of the above

ytdl('http://www.youtube.com/watch?v=aqz-KE-bpKQ')
  .pipe(fs.createWriteStream('video.mp4'));

API

ytdl(url, [options])

Attempts to download a video from the given url. Returns a readable stream. options can have the following, in addition to any getInfo() option and chooseFormat() option.

  • range - A byte range in the form {start: INT, end: INT} that specifies part of the file to download, ie {start: 10355705, end: 12452856}. Not supported on segmented (DASH MPD, m3u8) formats.
  • This downloads a portion of the file, and not a separately spliced video.
  • begin - What time in the video to begin. Supports formats 00:00:00.000, 0ms, 0s, 0m, 0h, or number of milliseconds. Example: 1:30, 05:10.123, 10m30s.
  • For live videos, this also accepts a unix timestamp or Date object, and defaults to Date.now().
  • This option is not very reliable for non-live videos, see #129 and #219.
  • liveBuffer - How much time buffer to use for live videos in milliseconds. Default is 20000.
  • highWaterMark - How much of the video download to buffer into memory. See node's docs for more. Defaults to 512KB.
  • dlChunkSize - When the chosen format is video only or audio only, the download is separated into multiple chunks to avoid throttling. This option specifies the size of each chunk in bytes. Setting it to 0 disables chunking. Defaults to 10MB.

Event: info

Emitted when the video's info is fetched, along with the chosen format to download.

Event: progress

  • number - Chunk length in bytes or segment number.
  • number - Total bytes or segments downloaded.
  • number - Total bytes or segments.

Emitted whenever a new chunk is received. Passes values describing the download progress.

miniget events

All miniget events are forwarded and can be listened to from the returned stream.

Stream#destroy()

Call to abort and stop downloading a video.

async ytdl.getBasicInfo(url, [options])

Use this if you only want to get metainfo from a video.

async ytdl.getInfo(url, [options])

Gets metainfo from a video. Includes additional formats, and ready to download deciphered URL. This is what the ytdl() function uses internally.

options can have the following

  • requestOptions - Anything to merge into the request options which miniget is called with, such as headers.
  • requestCallback - Provide a callback function that receives miniget request stream objects used while fetching metainfo.
  • lang - The 2 character symbol of a language. Default is en.

ytdl.downloadFromInfo(info, options)

Once you have received metadata from a video with the ytdl.getInfo function, you may pass that information along with other options to this function.

ytdl.chooseFormat(formats, options)

Can be used if you'd like to choose a format yourself. Throws an Error if it fails to find any matching format.

options can have the following

  • quality - Video quality to download. Can be an itag value, a list of itag values, or one of these strings: highest/lowest/highestaudio/lowestaudio/highestvideo/lowestvideo. highestaudio/lowestaudio try to minimize video bitrate for equally good audio formats while highestvideo/lowestvideo try to minimize audio respectively. Defaults to highest, which prefers formats with both video and audio.

    A typical video's formats will be sorted in the following way using quality: 'highest'

  itag container quality codecs                 bitrate  audio bitrate
  18   mp4       360p    avc1.42001E, mp4a.40.2 696.66KB 96KB
  137  mp4       1080p   avc1.640028            4.53MB
  248  webm      1080p   vp9                    2.52MB
  136  mp4       720p    avc1.4d4016            2.2MB
  247  webm      720p    vp9                    1.44MB
  135  mp4       480p    avc1.4d4014            1.1MB
  134  mp4       360p    avc1.4d401e            593.26KB
  140  mp4               mp4a.40.2                       128KB

format 18 at 360p will be chosen first since it's the highest quality format with both video and audio. If you'd like a higher quality format with both video and audio, see the section on handling separate streams.

  • filter - Used to filter the list of formats to choose from. Can be audioandvideo or videoandaudio to filter formats that contain both video and audio, video to filter for formats that contain video, or videoonly for formats that contain video and no additional audio track. Can also be audio or audioonly. You can give a filtering function that gets called with each format available. This function is given the format object as its first argument, and should return true if the format is preferable.
  // Example with custom function.
  ytdl(url, { filter: format => format.container === 'mp4' })
  • format - Primarily used to download specific video or audio streams. This can be a specific format object returned from getInfo.
  • Supplying this option will ignore the filter and quality options since the format is explicitly provided.
// Example of choosing a video format.
let info = await ytdl.getInfo(videoID);
let format = ytdl.chooseFormat(info.formats, { quality: '134' });
console.log('Format found!', format);

ytdl.filterFormats(formats, filter)

If you'd like to work with only some formats, you can use the filter option above.

// Example of filtering the formats to audio only.
let info = await ytdl.getInfo(videoID);
let audioFormats = ytdl.filterFormats(info.formats, 'audioonly');
console.log('Formats with only audio: ' + audioFormats.length);

ytdl.validateID(id)

Returns true if the given string satisfies YouTube's ID format.

ytdl.validateURL(url)

Returns true if able to parse out a valid video ID.

ytdl.getURLVideoID(url)

Returns a video ID from a YouTube URL. Throws an Error if it fails to parse an ID.

ytdl.getVideoID(str)

Same as the above ytdl.getURLVideoID(), but can be called with the video ID directly, in which case it returns it. This is what ytdl uses internally. Throws an Error if it fails to parse an ID.

ytdl.version

The version string taken directly from the package.json.

Limitations

ytdl cannot download videos that fall into the following

  • Regionally restricted (requires a proxy)
  • Private (if you have access, requires cookies)
  • Rentals (if you have access, requires cookies)
  • YouTube Premium content (if you have access, requires cookies)
  • Only HLS Livestreams are currently supported. Other formats will get filtered out in ytdl.chooseFormats

Generated download links are valid for 6 hours, and may only be downloadable from the same IP address.

Handling Separate Streams

Typically 1080p or better videos do not have audio encoded with it. The audio must be downloaded separately and merged via an encoding library. ffmpeg is the most widely used tool, with many Node.js modules available. Use the format objects returned from ytdl.getInfo to download specific streams to combine to fit your needs. Look at example/ffmpeg.js for an example on doing this.

What if it stops working?

YouTube updates their website all the time, it's not that rare for this to stop working. If it doesn't work for you and you're using the latest version, feel free to open up an issue. Make sure to check if there isn't one already with the same error.

Run the tests at test/irl-test.js to make sure this is really an issue with ytdl-core.

npm run test:irl

These tests are not mocked, they try to start downloading a few videos. If these fail, then it's time to debug. If the error you're getting is signature deciphering, check lib/sig.js. Otherwise, the error is likely within lib/info.js.

Install

npm install ytdl-core@latest

Or for Yarn users:

yarn add ytdl-core@latest

Make sure you're installing the latest version of ytdl-core to keep up with the latest fixes.

If you're using a bot or app that uses ytdl-core such as ytdl-core-discord or discord-player, it may be dependent on an older version. To update its ytdl-core version, that library has to update its package.json file, you can't simply change the version on your project's package.json, the app will still use its own older version of ytdl-core.

Look in their repo to see if they already have an active pull request that updates ytdl-core. If they don't, open an issue asking them to update ytdl-core, or better yet, fork the project and submit a pull request with the updated version.

While you wait for the pull reques to merge, you can point to its branch in your package.json

  "ytdl-core-discord": "amishshah/ytdl-core-discord#dependabot/npm_and_yarn/ytdl-core-2.0.1"

Update Checks

The issue of using an outdated version of ytdl-core became so prevalent, that ytdl-core now checks for updates at run time, and every 12 hours. If it finds an update, it will print a warning to the console advising you to update. Due to the nature of this library, it is important to always use the latest version as YouTube continues to update.

If you'd like to disable this update check, you can do so by providing the YTDL_NO_UPDATE env variable.

env YTDL_NO_UPDATE=1 node myapp.js

Related Projects

  • ytdl - A cli wrapper of this.
  • pully - Another cli wrapper of this aimed at high quality formats.
  • ytsr - YouTube video search results.
  • ytpl - YouTube playlist and channel resolver.

Tests

Tests are written with mocha

npm test
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文