toMedia
基础用法

格式选择

yt-dlp 格式选择字符串(-f)完整语法指南

格式选择是 yt-dlp 的核心功能之一。通过 -f 参数(或 Python 的 format 选项),你可以精确控制下载什么格式、什么画质的视频和音频。

查看可用格式

# 列出所有可用格式
yt-dlp -F "URL"
import yt_dlp

with yt_dlp.YoutubeDL({'skip_download': True}) as ydl:
    info = ydl.extract_info("URL", download=False)
    ydl.list_formats(info)
格式列表输出
ID   EXT  RESOLUTION  FPS  FILESIZE    TBR  PROTO VCODEC        ACODEC
─────────────────────────────────────────────────────────────────────────
139  m4a   audio only    0.73MiB   49k  https audio only    mp4a.40.5
140  m4a   audio only    1.93MiB  129k  https audio only    mp4a.40.2
251  webm  audio only    1.98MiB  132k  https audio only    opus
134  mp4   640x360     30    2.68MiB  179k  https avc1.4d401e
136  mp4   1280x720    30    8.91MiB  594k  https avc1.4d401f
137  mp4   1920x1080   30   16.44MiB 1095k  https avc1.640028
248  webm  1920x1080   30   11.02MiB  734k  https vp9

格式字符串语法

基础选择

格式字符串说明
best最佳单文件格式(包含视频+音频)
worst最差质量(节省流量)
bestvideo最佳视频流(可能不含音频)
bestaudio最佳音频流
bestvideo+bestaudio最佳视频 + 最佳音频(需要合并)

合并语法

+ 将视频流和音频流合并:

  • bestvideo+bestaudio — 最佳视频 + 最佳音频
  • 137+140 — 指定格式 ID 合并

回退语法

/ 指定备用格式:

  • bestvideo+bestaudio/best — 优先分离流合并,不行就用单文件最佳

过滤语法

在格式后添加 [条件] 进行过滤:

条件说明示例
[height<=1080]高度不超过 1080bestvideo[height<=1080]
[height>=720]高度至少 720bestvideo[height>=720]
[ext=mp4]扩展名为 mp4bestvideo[ext=mp4]
[fps<=30]帧率不超过 30bestvideo[fps<=30]
[vcodec=avc1]视频编码为 H.264bestvideo[vcodec^=avc1]
[acodec=mp4a]音频编码为 AACbestaudio[acodec^=mp4a]
[filesize<100M]文件小于 100MBbest[filesize<100M]

^= 表示"以...开头"匹配,因为编码器名称通常有细分版本(如 avc1.640028)。

常用格式组合

# 1080p MP4(最常用)
yt-dlp -f "bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]" "URL"

# 720p 省流量
yt-dlp -f "bestvideo[height<=720]+bestaudio/best[height<=720]" "URL"

# 仅 H.264 编码(兼容性最好)
yt-dlp -f "bestvideo[vcodec^=avc1]+bestaudio[acodec^=mp4a]/best" "URL"

# 最小文件(worst)
yt-dlp -f "worst" "URL"

# 只要音频(最佳质量)
yt-dlp -f "bestaudio" "URL"
import yt_dlp

# 1080p MP4
opts_1080p = {
    'format': 'bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]',
}

# 720p 省流量
opts_720p = {
    'format': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
}

# H.264 编码
opts_h264 = {
    'format': 'bestvideo[vcodec^=avc1]+bestaudio[acodec^=mp4a]/best',
}

with yt_dlp.YoutubeDL(opts_1080p) as ydl:
    ydl.download(["URL"])

格式排序(高级)

使用 -S 参数自定义排序优先级:

# 优先选择 h264 编码,其次选高分辨率
yt-dlp -S "codec:h264,res" "URL"

# 优先选择 mp4 容器,其次选文件大小
yt-dlp -S "ext:mp4:m4a,size" "URL"

# 优先选择 ≤1080p 的最高画质
yt-dlp -S "res:1080" "URL"

相关页面

On this page