在 youtube_dl 进度挂钩中获取 URL 的已下载视频

Get URL of downloaded video in youtube_dl progress hook

如何获取我正在使用 youtube_dl 下载的视频的 URL?

我可以使用进度挂钩获取下载的其他特征,例如文件路径:

def progress_hook(response):
    if response["status"] == "finished":
        file_name = response["filename"]

ydl_opts = {
    'progress_hooks': [progress_hook]
}

我还想获取文件来源的 URL。我不知道该怎么做。像 url = response["url"] 这样的东西会很好,但是 there aren't very many options 有进度挂钩。

由于似乎没有办法做到这一点,我将我的程序重组为一次只下载一个,所以我很明确地知道正在下载哪个。

要使用它,您需要创建它的一个实例,将要下载的 URL 列表传递给构造函数。

然后,当您准备就绪时,您可以对该对象调用 start_download_process。它将等到当前曲目完成并且 progress_hook 完成后再下载另一个曲目。

class YoutubeManager:
    def __init__(self, url_list):
        self.base_url = "https://www.youtube.com"
        self.current_download_url = ""
        self.url_list = url_list

        self.currently_downloading = False
        self.current_download_count = 0

        ydl_opts = {
            'format': 'bestaudio/best',
            'noplaylist': True,
            'continue_dl': True,
            'progress_hooks': [self.progress_hook],
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192', }]
        }

        self.youtube_dl_manager = youtube_dl.YoutubeDL(ydl_opts)
        

    def start_download_process(self):
        self.currently_downloading = True
        self.current_download_count += 1

        with self.youtube_dl_manager as youtube_dl_manager:
            self.current_download_url = self.url_list.pop()
            youtube_dl_manager.download([self.base_url + self.current_download_url])

    def continue_download_process(self):
        self.current_download_count += 1
        with self.youtube_dl_manager as youtube_dl_manager:
            self.current_download_url = self.url_list.pop()
            youtube_dl_manager.download([self.base_url + self.current_download_url])

    def progress_hook(self, response):
        if response["status"] == "finished":
            file_name = response["filename"]
            print("Downloaded " + file_name)

            # You can do something with self.current_download_url and file_name here

            if len(self.url_list) != 0:
                self.continue_download_process()
            else:
                self.currently_downloading = False