HeyCHのブログ

慢性疲労のへいちゃんです

【C#】YouTube動画ダウンローダーを作ってみよう

YouTubeの動画をダウンロードすることは規約違反です。

しかしながら今回は試しに動画をダウンロードするツールを作ってみようと思います。

まずはWebBrowserの作成

WebBrowserでYouTubeの動画を開いて、Downloadするという形をとりたいので、
TextBoxを配置して、そこでEnterキーを押すとそこにジャンプするという感じにしています。

<Window x:Class="WebBrowserWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WebBrowserWpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="25"/>
                <ColumnDefinition Width="25"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="100"/>
            </Grid.ColumnDefinitions>
            <Button Grid.Column="0" Content="←" Click="Button_Click_1"/>
            <Button Grid.Column="1" Content="→" Click="Button_Click_2"/>
            <TextBox Grid.Column="2" Text="{Binding URL,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" KeyUp="TextBox_KeyUp"/>
            <Button Grid.Column="3" Content="Download" Click="Button_Click" IsEnabled="{Binding DownloadOK}"/>
        </Grid>
        <WebBrowser Grid.Row="1" x:Name="webBrowser1" Navigated="webBrowser1_Navigated"/>
    </Grid>
</Window>
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WebBrowserWpf {
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window {
        ViewModel vm;
        public MainWindow() {
            InitializeComponent();
            vm = new ViewModel();
            this.DataContext = vm;
            webBrowser1.Navigate(vm.URL);
        }

        private void TextBox_KeyUp(object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter) {
                webBrowser1.Navigate(vm.URL);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
              
        }

        private void webBrowser1_Navigated(object sender, NavigationEventArgs e) {
            vm.URL = e.Uri.AbsoluteUri;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e) {
            if (webBrowser1.CanGoBack) webBrowser1.GoBack();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e) {
            if (webBrowser1.CanGoForward) webBrowser1.GoForward();
        }
    }
    public class ViewModel : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnoPropertyChanged(string propertyName) {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        string _URL = "https://www.google.com/";
        public string URL {
            get {
                return _URL;
            }
            set {
                _URL = value;
                DownloadOK = Regex.IsMatch(_URL, @"\?v=([^&]+)");
                OnoPropertyChanged("URL");
            }
        }
        bool _DownloadOK = false;
        public bool DownloadOK {
            get {
                return _DownloadOK;
            }
            set {
                _DownloadOK = value;
                OnoPropertyChanged("DownloadOK");
            }
        }
    }
}

VideoLibraryを使って動画をダウンロード

VideoLibraryというライブラリを使って動画をダウンロードするわけですが、使うためには準備が必要です。
VideoLibraryはNugetパッケージマネージャーからダウンロードして使う事ができます。
ツール>Nugetパッケージマネージャー>ソリューションのNugetパッケージの管理を開きます
f:id:HeyCH:20200504011436p:plain
左上の「参照」を選択して「VideoLibrary」を検索します。
f:id:HeyCH:20200504011741p:plain
プロジェクトに☑を入れて、「インストール」を押します。
f:id:HeyCH:20200504011853p:plain
そうすると、VideoLibraryは.NET Framework 4.3.0を使用しているという事がわかります。
f:id:HeyCH:20200504012152p:plain
そのままインストールするとDLLがたっくさんできてしまうので、プロジェクトの.NET Frameworkを4.3.0にしたいのですが、対象のFrameworkは存在しませんでした。残念。
仕方ないので、そのままOKを押します。

使い方は上のusing がたくさん書いてあるところに

using VideoLibrary;

を追加して

        private void Button_Click(object sender, RoutedEventArgs e) {
            var youTube = YouTube.Default;
            var video = youTube.GetVideo(vm.URL);
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = video.FullName;
            if (sfd.ShowDialog() == true) {
                System.IO.File.WriteAllBytes(sfd.FileName, video.GetBytes());
            }
        }

こんな感じです。