Sunday 9 August 2020

How to download YouTube Videos using .NET

 Are you interested in downloading YouTube Videos?

Want to download YouTube Videos in device specific formats?
Need to have some fun while coding on interesting Stuff?


Yes, then you are at the right place! In this blog I am going to show you how we can download the Videos from YouTube URL in different formats. You can download the video from YouTube URL in these formats: .Mp4, .Flv, .3Gp, .WebM

Each YouTube video URL has a video id, which is appended to the URL as a query string. The name of the query string to get the video id is v. The typical YouTube video URL looks like this:

http://www.youtube.com/watch?v=aqkkByP8RDM

In the above URL, aqkkByP8RDM is the video id. To download the video from this URL, first we need to get some more detailed information about this video which includes video formats and video file URLs. The below URL can be helpful to get the more details about video:

http://www.youtube.com/get_video_info?video_id=aqkkByP8RDM

The above URL not only gives us the information about video formats and URLs, it also includes video title, description, viewers count, etc. 

All we need is extract the required information from the above URL and do download video file whichever the format you need. Here I am going to show you the step by step procedure to extract video formats and video file URLs for download a video.

 

For demonstration I have used the ASP.NET with C# as a language. You can use any other .NET language which ever you prefer. I have designed a small UI in ASP.NET which accepts the YouTube video URL from user:
 

<div>
  <
table>
   <
tr>
    <
td>
     YouTube URL:
    td>
    <
td>
     <
asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
    td>
   tr>
   <
tr>
    <
td>
    td>
    <
td>
     <
asp:Button ID="btnProcess" Text="Process" runat="server" OnClick="btnProcess_Click"
       Width
="100" />
    td>
   tr>
   <
tr>
    <
td>
      <
asp:DropDownList ID="ddlVideoFormats" runat="server" Visible="false">         

 asp:DropDownList>
    td>
    <
td>
      <
asp:Button ID="btnDownload" Text="Download" runat="server" 

OnClick="btnDownload_Click" Width="100" Visible="false" />
    td>
   tr>
 table>
 <
br />
 <
asp:Label ID="lblMessage" Text="" runat="server" />
div>

 

I have also added a button called Process button. The process button will get the detailed information about requested URL from YouTube and extracts the video formats and video URLs to download the video.

I am also showing these video formats and URLs in a DropDownList control, so that user can download a video in his preferred format.

The below code is used to get detailed information of YouTube URL and extracting the needed information to download a video:

protected void btnProcess_Click(object sender, EventArgs e)
{
  try
  {
    Uri videoUri = new Uri(txtYouTubeURL.Text);
    string videoID = HttpUtility.ParseQueryString(videoUri.Query).Get("v");
    string videoInfoUrl = "http://www.youtube.com/get_video_info?video_id=" + videoID;

 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(videoInfoUrl);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));

 

    string videoInfo = HttpUtility.HtmlDecode(reader.ReadToEnd());

 

    NameValueCollection videoParams = HttpUtility.ParseQueryString(videoInfo);

 

    if (videoParams["reason"] != null)
    {
      lblMessage.Text = videoParams["reason"];
      return;
    }

 

    string[] videoURLs = videoParams["url_encoded_fmt_stream_map"].Split(',');

 

    foreach (string vURL in videoURLs)
    {
      string sURL = HttpUtility.HtmlDecode(vURL);

 

      NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);
      string videoFormat = HttpUtility.HtmlDecode(urlParams["type"]);

 

      sURL = HttpUtility.HtmlDecode(urlParams["url"]);
      sURL += "&signature=" + HttpUtility.HtmlDecode(urlParams["sig"]);
      sURL += "&type=" + videoFormat;
      sURL += "&title=" + HttpUtility.HtmlDecode(videoParams["title"]);

 

      videoFormat = urlParams["quality"] + " - " + videoFormat.Split(';')[0].Split('/')[1];

 

      ddlVideoFormats.Items.Add(new ListItem(videoFormat, sURL));
    }

 

    btnProcess.Enabled = false;
    ddlVideoFormats.Visible = true;
    btnDownload.Visible = true;
    lblMessage.Text = string.Empty;
  }
  catch (Exception ex)
  {
    lblMessage.Text = ex.Message;
    lblMessage.ForeColor = Color.Red;
    return;
  }
}

 

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  lblMessage.Text = "Video downloaded on: " + DateTime.Now.ToString();
  lblMessage.ForeColor = Color.Green;
}

When you take a deep look at detailed information of YouTube video URL, you can find url_encoded_fmt_stream_map parameter has many video URLs and each video URL 

is separated by comma (,) as a delimiter. And, each URL has the video format and quality of it.

Quality parameter tells us the size of video like, small, medium, large, high definition (HD)

Once you extract the direct video URLs from the parameter, you are ready to download it. Below code is used to download the video (not only video, it can be used to for any file download) from direct URL:

protected void btnDownload_Click(object sender, EventArgs e)
{
  try
  {
    string sURL = ddlVideoFormats.SelectedValue;

 

    if (string.IsNullOrEmpty(sURL))
    {
      lblMessage.Text = "Unable to locate the Video.";
      return;
    }

 

    NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);

 

    string videoTitle = urlParams["title"] + " " + ddlVideoFormats.SelectedItem.Text;
    string videoFormt = HttpUtility.HtmlDecode(urlParams["type"]);
    videoFormt = videoFormt.Split(';')[0].Split('/')[1];

 

    string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
    string sFilePath = string.Format(Path.Combine(downloadPath, "Downloads\\{0}.{1}"),    videoTitle, videoFormt);

 

    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    webClient.DownloadFileAsync(new Uri(sURL), sFilePath);
  }
  catch (Exception ex)
  {
    lblMessage.Text = ex.Message;
    lblMessage.ForeColor = Color.Red;
    return;
  }
}

The above code will downloads the requested video using WebClient class and place it into Downloads folder of your machine.

Below is the screenshot of rendered UI on my webpage and it also contains the processed video formats of sample YouTube URL.

YouTube

Happy Coding…!

No comments:

Post a Comment