【问题标题】:Download you tube video using c#?使用 c# 下载 youtube 视频?
【发布时间】:2017-10-22 22:11:32
【问题描述】:

我正在尝试使用 c# 代码下载你的视频,但我没有得到正确的代码。我搜索了很多链接,但没有得到任何正确的链接和代码。

我想用 c# 代码在我的本地文件夹中下载你的视频。我尝试了一个链接,但该代码只是在我的本地文件夹中获取空视频,所以任何人都知道如何做到这一点。

以下是我目前尝试过的代码。

var VedioUrl = "https://www.youtube.com/embed/" + objYouTube.VideoID + ".mp4";

WebRequest MyRequest = HttpWebRequest.Create(VedioUrl);
WebResponse MyResponse = MyRequest.GetResponse();
string RealURL = MyResponse.ResponseUri.ToString();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RealURL);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
StreamWriter writer = new StreamWriter(Server.MapPath("~/youtube/" + objYouTube.VideoID + ".mp4"), true);
writer.Write(readStream.ReadToEnd());
writer.Close();

这是我要下载的视频网址:“https://www.youtube.com/embed/UCsiNPbLbwZk43FOCRrdKBlA.mp4

【问题讨论】:

  • youtube-dl 是一个不错的开源解决方案。您可以将其添加到您的应用中。
  • @AchaBill 但是如何使用它任何想法请给我一些提示。
  • @AchaBill 我在这个问题中传递了这个beloe url,它是否正确?你必须用你的想法这样编码,所以请在这篇文章中给我新的答案。
  • 大家有什么想法,请让我知道几天后我将面临这个问题。

标签: c# youtube


【解决方案1】:

我找到了使用 c# 代码下载你的视频的解决方案。

首先需要在 Visual Studio 的 NuGet 包管理器控制台上安装“libvideo”。

在包管理器控制台上触发此命令:

Install-Package VideoLibrary

首先在你的控制器顶部添加这个命名空间:

using VideoLibrary;

现在这里只写代码并传递 url 链接:

var VedioUrl = "https://www.youtube.com/embed/" + objYouTube.VideoID + ".mp4";
var youTube = YouTube.Default;
var video = youTube.GetVideo(VedioUrl);
System.IO.File.WriteAllBytes(Server.MapPath("~/youtube/" + video.FullName + ".mp4"), video.GetBytes());

【讨论】:

    【解决方案2】:

    您可以在您的应用中嵌入youtube-dl
    它提供了广泛的 Youtube 下载选项。

    基本上,你会做这样的事情。

    using System;
    using System.Diagnostics;
    using System.ComponentModel;
    
    namespace MyProcessSample
    {
        class MyProcess
        {
            public static void Main()
            {
                Process myProcess = new Process();
    
                try
                {
                    myProcess.StartInfo.UseShellExecute = false;
                    myProcess.StartInfo.FileName = @"yourpath\youtube-dl.exe";
                    myProcess.StartInfo.CreateNoWindow = false;
                    myProcess.StartInfo.Arguments = "https://www.youtube.com/watch?v=KFqrp4KSxio";
                    myProcess.Start();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
    

    你可以使用这个C# wapper for youtube-dl
    您可以对其进行扩展以满足您的需求。

    Process Class

    【讨论】:

    • 所以我需要将 youtube-dl refrence 添加到我们的 .net c# 解决方案中,对吗?
    • 您需要二进制文件。即可执行文件。你可以使用这个C# wrapper
    • 好的,我会尝试使用您的解决方案,然后遇到任何问题,请您帮忙,我只给您一个 ping ok
    【解决方案3】:

    如需更多最新解决方案,请查看YoutubeExplode。它提供了丰富的 API 来查询和下载 Youtube 视频,并且与其他库不同,它仍在积极维护中。

    【讨论】:

      【解决方案4】:

      在 Visual Studio 的 NuGet 包管理器控制台上安装 "libvideo" 之后。

      并下载 ffmpeg 以合并音频和视频以获得最佳输出。

      按照此代码:

      using System;
      using System.Diagnostics;
      using System.IO;
      using System.Net;
      using VideoLibrary;
      
      namespace you_tube_download
      {
          class Program
          {
              static void Main(string[] args)
              {
                  try
                  {
                  Console.WriteLine("write url video : ");
                  string url = Console.ReadLine();
                  string information = "";
                  var videos = YouTube.Default.GetAllVideos(url);
                  int hightaudio = 1;
                  int hightvideo = 1;
                  Console.WriteLine("\nlist all format \n");
                  foreach (var item in videos)//write all file on this url
                   {
                      Console.WriteLine(item.Resolution+","+item.Format + "," + item.AudioFormat + "," + item.AudioBitrate + "," + item.ContentLength + "," + item.AdaptiveKind);
                      if (item.AdaptiveKind.ToString() == "Audio" && item.AudioBitrate > hightaudio)
                      {
                          hightaudio = item.AudioBitrate;
                          information = item.AudioFormat + "," + item.AudioBitrate+","+item.ContentLength;
                      }
                      if (item.Resolution > hightvideo)
                      {
                          hightvideo = item.Resolution;
                      }
                  }
                   Console.WriteLine("\ndownload high video resolotion {0} and high audio bitrate {1}",hightvideo,hightaudio);
                   string[] split = information.Split(',');
                  foreach (var item in videos)//download audio
                  {
                      if (split[0]== item.AudioFormat.ToString() && split[1] == item.AudioBitrate.ToString() && split[2] == item.ContentLength.ToString())
                      {
                          Console.WriteLine("\ndownload audio with bitrate {0} and size {1}MB",item.AudioBitrate, Math.Round((double)item.ContentLength / 1000000, 2));
                          downloadbest(item, Directory.GetCurrentDirectory() + "\\file123456798.mp3");
                          Console.Write("end\n");
                      }
                  }
                  foreach (var item in videos)//download video
                  {
                      if (item.Resolution==hightvideo)
                      {
                          Console.WriteLine("\ndownload video with Resolution {0} and size {1}MB", item.Resolution, Math.Round((double)item.ContentLength/1000000,2));
                          downloadbest(item, Directory.GetCurrentDirectory() + "\\file123456798.mp4");
                          Console.Write("end\n");
                          break;
                      }
                  }
                  Console.WriteLine("wait for marge");
                  combine();
                  File.Delete(Directory.GetCurrentDirectory() + "\\file123456798.mp3");
                  File.Delete(Directory.GetCurrentDirectory() + "\\file123456798.mp4");
                  Console.WriteLine("press any key to continue...");
                  Console.ReadKey();
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("\n\n\n\n" + ex);
                      Console.ReadKey();
                  }
                  Process.Start(Directory.GetCurrentDirectory());
              }
              static void combine()
              {
                  Process p = new Process();
                  p.StartInfo.FileName = "ffmpeg.exe";
                  p.StartInfo.Arguments = "-i \"" + Directory.GetCurrentDirectory() + "\\file123456798.mp4\" -i \"" + Directory.GetCurrentDirectory() + "\\file123456798.mp3\" -preset veryfast  \"" + Directory.GetCurrentDirectory() + "\\final.mp4\"";
                  p.Start();
                  p.WaitForExit();
              }
              static void downloadbest(YouTubeVideo y, string patch)
              {
                  int total = 0;
                  FileStream fs =null;
                  Stream streamweb = null;
                  WebResponse w_response = null;
                  try
                  {
                      WebRequest w_request = WebRequest.Create(y.Uri);
                      if (w_request != null)
                      {
                          w_response = w_request.GetResponse();
                          if (w_response != null)
                          {
                              fs = new FileStream(patch, FileMode.Create);
                              byte[] buffer = new byte[128*1024];
                              int bytesRead = 0;
                              streamweb = w_response.GetResponseStream();
                              Console.WriteLine("Download Started");
                              do
                              {
                                  bytesRead = streamweb.Read(buffer, 0, buffer.Length);
                                  fs.Write(buffer, 0, bytesRead);
                                  total += bytesRead;
                                  Console.Write($"\rDownloading ({Math.Round(((double)total/(int)y.ContentLength) * 100, 2)}%) {total}/{y.ContentLength}     ");
                              } while (bytesRead > 0);
                              Console.WriteLine("\nDownload Complete");
                          }
                      }
      
      
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("\n\n\n\n" + ex);
                      Console.ReadKey();
                      Process.Start(Directory.GetCurrentDirectory());
                  }
                  finally
                  {
                      if (w_response != null) w_response.Close();
                      if (fs != null) fs.Close();
                      if (streamweb != null) streamweb.Close();
                  }
              }
          }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 2018-08-19
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 2017-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多