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

如何用yt_dlp获取YouTube音频流以替代存在问题的pafy?

使用yt_dlp获取YouTube音频流列表的解决方案

1. 安装yt_dlp

先确保安装最新版的yt_dlp:

pip install --upgrade yt-dlp

2. 核心代码实现

以下是可直接集成到GUI播放器的音频流获取示例:

import yt_dlp

def get_youtube_audio_streams(video_url):
    # 配置yt_dlp参数,聚焦音频流提取
    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'no_warnings': True,
        'extract_flat': False,  # 确保拉取完整的流详情
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        # 获取视频的完整元数据
        video_info = ydl.extract_info(video_url, download=False)
        
        # 过滤出所有含音频编码的流
        audio_streams = [
            stream for stream in video_info['formats']
            if stream.get('acodec') != 'none'
        ]

        # 整理成播放器可用的结构化信息
        formatted_streams = []
        for stream in audio_streams:
            formatted_streams.append({
                'url': stream['url'],
                'bitrate': f"{stream.get('abr', '未知')} kbps",
                'format': stream.get('ext', '未知'),
                'audio_codec': stream.get('acodec', '未知')
            })
        
        return formatted_streams

# 测试调用
if __name__ == "__main__":
    test_url = "https://www.youtube.com/watch?v=示例视频ID"
    streams = get_youtube_audio_streams(test_url)
    for idx, stream in enumerate(streams):
        print(f"流 {idx+1}:")
        print(f"  地址: {stream['url']}")
        print(f"  音质: {stream['bitrate']}")
        print(f"  格式: {stream['format']}\n")

3. 关键细节说明

  • 参数配置:format: 'bestaudio/best' 优先获取高音质流,但仍会返回所有可用音频选项;quiet 和 no_warnings 用于屏蔽控制台冗余输出,适配GUI场景。
  • 流过滤逻辑:通过acodec != 'none'精准筛选音频流,避免混入无音频的视频流。
  • 信息整理:提取了播放器核心需要的字段,可根据你的GUI界面需求增删返回字段。

4. 进阶调整

如果需要指定格式(比如仅MP3),可以修改过滤规则:

# 仅保留MP3格式的音频流
audio_streams = [
    stream for stream in video_info['formats']
    if stream.get('acodec') != 'none' and stream.get('ext') == 'mp3'
]

或者直接在参数中限定格式:

ydl_opts = {
    'format': 'bestaudio[ext=mp3]/bestaudio',
    # 其他参数不变
}

内容的提问来源于stack exchange,提问作者Willem van Houten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:10:39