0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【GUI付きで簡単】yt-dlpを使ってYouTube動画をMP4/MP3形式でダウンロードする方法

Posted at

背景:なぜ今「yt-dlp」を使うのか?

近年、動画コンテンツの保存やオフライン視聴のニーズが高まっており、それに伴ってyt-dlpのような高機能ダウンローダーの需要が急上昇しています。特にyt-dlpは、旧来のyoutube-dlの後継として機能拡張が頻繁に行われており、実務・開発・自動化の場面でも活躍しています。

本記事では、実際に販売予定のGUI付きYouTubeダウンローダーアプリのコードを元に、初心者でも簡単に実装可能なyt-dlpの活用方法を解説します。

技術的背景:yt-dlpとは?

yt-dlpはPython製のコマンドラインベースの動画ダウンローダーで、YouTubeをはじめとした1000以上の動画サイトに対応しています。特徴として:

  • 複雑なフォーマット選択機能
  • FFmpegとの連携によるMP3/MP4への自動変換
  • 広告・ライブ配信対応・チャプター分割などの高度なオプション
  • youtube-dlとの互換性を維持しつつ、拡張が積極的に行われている

よくある課題・エラーとその対処法

yt-dlpを実務で使う際に遭遇しやすい課題には以下のようなものがあります:

  • URLの種類により形式取得に失敗する:プレイリストURLやショート動画URLは特別な処理が必要
  • 進捗率が表示されない:一部の動画では全体サイズが取得できず、進捗が「不明」と表示される
  • FFmpegが正しく認識されていない:Windows環境ではパスの指定ミスが原因
  • 日本語ファイル名が文字化け:Windows標準端末でのエンコード設定が原因

※GUIで実装する際には、非同期処理やキューの扱いにも注意が必要です

Python + yt-dlp + tkinter で実装するGUIアプリ

以下は、筆者が作成・販売しているGUI付きYouTubeダウンローダーの主要コードです。


# ダウンロードを実行するメイン関数
def download_video(url: str, save_path: str, progress_queue: queue.Queue, output_formats: list):
    def progress_hook(d):
        if d['status'] == 'downloading':
            downloaded = d.get('downloaded_bytes', 0)
            total = d.get('total_bytes', None) or d.get('total_bytes_estimate', None)
            percentage = int((downloaded / total) * 100) if total else '不明'
            progress_queue.put(percentage)

    for output_format in output_formats:
        if output_format == 'mp3':
            ydl_opts = {
                'format': 'bestaudio',
                'outtmpl': os.path.join(save_path, '%(title)s_audio.%(ext)s'),
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }],
                'ffmpeg_location': 'C:\\Users\\user\\ffmpeg-7.1-essentials_build\\bin\\ffmpeg.exe',
                'progress_hooks': [progress_hook],
                'noplaylist': True,
            }
        else:  # mp4
            ydl_opts = {
                'format': 'bv*+ba/b',
                'outtmpl': os.path.join(save_path, '%(title)s_video.%(ext)s'),
                'merge_output_format': 'mp4',
                'postprocessors': [{
                    'key': 'FFmpegVideoRemuxer',
                    'preferedformat': 'mp4',
                }],
                'ffmpeg_location': 'C:\\Users\\user\\ffmpeg-7.1-essentials_build\\bin\\ffmpeg.exe',
                'progress_hooks': [progress_hook],
                'noplaylist': True,
            }

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])

このように、形式ごとにオプションを分けて実装し、ユーザーの選択に応じて動的に処理を分岐させています。

GUIの全体構成:tkinterによるユーザー操作の簡素化

アプリは以下の3構成で構成されています:

  • URL入力欄とチェックボックスで出力形式を指定
  • Startボタンで非同期処理(スレッド)によるダウンロード開始
  • プログレスバー+進捗表示(Queueにて逐次更新)

内部的には`queue.Queue`でスレッド間の進捗通信を行い、GUI側の更新は`after()`関数で定期監視しています。


def update_progress(self):
    if self.progress_queue is not None:
        while True:
            try:
                progress = self.progress_queue.get_nowait()
            except queue.Empty:
                break

            if isinstance(progress, str) and progress.startswith('ERROR:'):
                messagebox.showerror("エラー", progress)
                ...
            elif progress == 'COMPLETE_ALL':
                self.progress_var.set(100)
                self.progress_text.set("100%")
                messagebox.showinfo("完了", "ダウンロード完了")
                ...
            elif isinstance(progress, int):
                self.progress_var.set(progress)
                self.progress_text.set(f"{progress}%")

    self.root.after(100, self.update_progress)

ベストプラクティス・運用上の注意

  • yt-dlp本体のバージョンを定期的に更新すること(YouTube側の仕様変更に追従)
  • FFmpegのパスは絶対パスで指定し、環境によって変更可能にする
  • 例外処理は必ず行う(yt-dlp.exceptions.DownloadError など)
  • GUIの進捗表示はスレッドセーフに設計すること
  • OS依存パスやエンコードの罠に注意

まとめと今後の展望

本記事では、yt-dlpとPythonでGUIベースのYouTubeダウンローダーを構築する手順を紹介しました。 このアプリケーションは、以下のような場面で有用です:

  • 動画資料のローカル保存(学習用途など)
  • 音声抽出によるポッドキャスト化
  • ノーコードな社内ツールとして展開

今後は、次のような機能強化が見込まれます:

  • 自動チャプター分割
  • 複数URLの一括ダウンロード
  • 検索→ダウンロードまで一貫した自動化GUI

【商品紹介】このアプリを試してみませんか?

今回紹介したGUIアプリは、現在Boothにて販売準備中です。GUIベースで初心者でも簡単に使え、MP3・MP4両方の出力に対応しています。

販売ページ:YouTubeダウンローダー(MP4/MP3対応)

  • 価格:500円
  • 形式:Windows対応(Python + Tkinterベース)
  • 内容:GUIアプリ+ffmpeg導入手順付きReadMe

興味のある方はぜひチェックしてみてください!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?