Click here to Skip to main content
16,016,623 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Been some time since I last posted something here so I thought I could post my latest project.

It's a youtube downloader written in C#.

Some code, I started with making a DLL which should contain all youtube functions I needed.

YoutubeDownload.DLL
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace YoutubeDownloadDLL
{
    static public class YoutubeDownload
    {
        public enum formatType
        {
            mp3 = 0,
            mp4 = 1,
            flv = 2,
            mpg = 3,
            avi = 4
        }

        /// <summary>
        /// Gets a downloadable youtube link
        /// </summary>
        /// <param name="strUrl">the url to the video</param>
        /// <returns>returns the link on success, else it returns string.empty</returns>
        static public string GetYoutubeLink(string strUrl)
        {
            try
            {
                //Get the key from the url
                string strKey = strUrl.Substring(strUrl.LastIndexOf("v=") + 2, 11);

                if (strKey == string.Empty)
                    throw new ArgumentException();

                //Get the token from the video info
                Uri infoUri = new Uri("http://youtube.com/get_video_info?video_id=" + strKey);
                string strToken = getTokenFromUri(infoUri);

                if (strToken == string.Empty)
                    return string.Empty;

                string strDownloadLink =
                    "http://www.youtube.com/get_video.php?video_id=" + strKey + "&t=" + strToken + "&fmt=18";
                
                return strDownloadLink;
            }
            catch (Exception ex)
            {
                //Handle exception
            }
            return string.Empty;
        }

        /// <summary>
        /// This function requires ffmpeg, make a folder called ffmpeg in your project folder
        /// </summary>
        /// <param name="strInputFile">path to input file, .mp4 (e.g. file1.mp4)</param>
        /// <param name="strOutPutFile">path to output file, .mp3 (e.g. file2.mp3)</param>
        /// <returns></returns>
        static public int EncodeFormatFromMp4ToMp3(string strInputFile,
                                                    string strOutPutFile,
                                                    bool bolKeepInputFile)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "ffmpeg.EXE";
            startInfo.Arguments = "-i \"" + strInputFile + "\" -vn -ac 1 \"" + strOutPutFile + "\"";
            startInfo.CreateNoWindow = true;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process prcProcess = new Process();
            prcProcess.StartInfo = startInfo;
            prcProcess.Start();

            prcProcess.WaitForExit();
            prcProcess.Close();

            if (!bolKeepInputFile)
            {
                File.Delete(strInputFile);
            }

            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strDownloadLink">download link</param>
        /// <param name="objFormat">the format you want to save the file as</param>
        /// <param name="strOutputFileName">output file name</param>
        /// <returns></returns>
        static public int CreateFileFromYoutubeDownloadLink(string strDownloadLink,
                                                            string strOutputFileName)
        {
            Uri objUri = new Uri(strDownloadLink);

            //Get file content
            WebRequest wrRequest = WebRequest.Create(objUri);
            WebResponse wrResponse = wrRequest.GetResponse();
            Stream objStream = wrResponse.GetResponseStream();

            FileStream fsStream = new FileStream(strOutputFileName, FileMode.Create);
            byte[] bteRead = new byte[256];

            int iCount = objStream.Read(bteRead, 0, bteRead.Length);

            while (iCount > 0)
            {
                fsStream.Write(bteRead, 0, iCount);
                iCount = objStream.Read(bteRead, 0, bteRead.Length);
            }

            fsStream.Close();
            objStream.Close();
            wrResponse.Close();


            return 0;
        }

        /// <summary>
        /// Gets the title of the youtube link
        /// </summary>
        /// <param name="strUrl">url to youtube video</param>
        /// <returns>return title on success</returns>
        static public string GetTitleFromYoutubeLink(string strUrl)
        {
            try
            {
                Uri objUri = new Uri(strUrl);

                //Get file content
                WebRequest wrRequest = WebRequest.Create(objUri);
                WebResponse wrResponse = wrRequest.GetResponse();
                Stream objStream = wrResponse.GetResponseStream();
                StreamReader objReader = new StreamReader(objStream);

                //Hopefully got it!
                string strFileContent = objReader.ReadToEnd();

                //Calculate the title length
                int iTitlePos = strFileContent.LastIndexOf("<meta name=\"title\" content=\"") + 28;
                int iEndTitlePos = strFileContent.IndexOf("\">", iTitlePos);
                int iDifference = iEndTitlePos - iTitlePos;

                //Moving on to finding the title
                string strTitle = strFileContent.Substring(iTitlePos, iDifference);

                objStream.Close();
                objReader.Close();
                wrResponse.Close();

                return strTitle;
            }
            catch (Exception ex)
            {
                //ex
            }
            return string.Empty;
        }

        static private string getTokenFromUri(Uri objUri)
        {
            //Get file content
            WebRequest wrRequest = WebRequest.Create(objUri);
            WebResponse wrResponse = wrRequest.GetResponse();
            Stream objStream = wrResponse.GetResponseStream();
            StreamReader objReader = new StreamReader(objStream);

            //Hopefully got it!
            string strFileContent = objReader.ReadToEnd();

            //Calculate the token length
            int iTokenPos = strFileContent.LastIndexOf("&token=") + 7;
            int iThumbPos = strFileContent.LastIndexOf("&thumbnail_url=");
            int iDifference = iThumbPos - iTokenPos;

            //Moving on to finding the token
            string strToken = strFileContent.Substring(iTokenPos, iDifference);

            objReader.Close();
            objStream.Close();
            wrResponse.Close();

            if (strToken == string.Empty)
                return string.Empty;
            else
                return strToken;
        }
    }
}



As you can see I use ffmpeg to convert from mp4 to mp3, do you guys have any better ways of converting files other than using ffmpeg.exe?
Here is a picture of the application running:
Screen shot:












C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using YoutubeDownloadDLL;

namespace KekTube_Downloader
{
    public partial class frmMain : Form
    {
        private static int iPercentProgress;
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
        private delegate void SetTextCallback(string strText);
        private Thread thrDownload;

        public frmMain()
        {
            InitializeComponent();
        }

        private void txtYoutubeLink_Enter(object sender, EventArgs e)
        {
            this.txtYoutubeLink.Text = "";
        }

        private void txtYoutubeLink_Leave(object sender, EventArgs e)
        {
            if (this.txtYoutubeLink.Text == "")
                this.txtYoutubeLink.Text = "URL to Youtube movie";
        }

        private void txtYoutubeLink_TextChanged(object sender, EventArgs e)
        {
            if (this.txtYoutubeLink.Text.IndexOf("watch") > 0)
            {
                this.lblTitle.Text = YoutubeDownload.GetTitleFromYoutubeLink(this.txtYoutubeLink.Text);
                this.lblOrgTitle.Text = "video4.mp4";

                string strFormat = string.Empty;

                if (cboMp3.Checked)
                    strFormat = ".mp3";
                else if (cboMp4.Checked)
                    strFormat = ".mp4";
                else
                    strFormat = ".mp4";

                if (this.cboCustom.Checked)
                {
                    this.lblSaveAs.Text = this.txtCustomName.Text + strFormat;
                }
                else
                {
                    this.lblSaveAs.Text = this.lblTitle.Text + strFormat;
                }
            }
        }

        private void cboMp4_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cboMp4.Checked)
            {
                //Set all to false except for the format the user wants
                this.cboMp3.Checked = false;

                this.lblSaveAs.Text = this.lblSaveAs.Text.Substring(0, this.lblSaveAs.Text.Length - 1) + "4";
            }
        }

        private void cboMp3_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cboMp3.Checked)
            {
                //Set all to false except for the format the user wants
                this.cboMp4.Checked = false;

                this.lblSaveAs.Text = this.lblSaveAs.Text.Substring(0, this.lblSaveAs.Text.Length - 1) + "3";
            }
        }

        private void cboCustom_CheckedChanged(object sender, EventArgs e)
        {
            string strFormat = string.Empty;

            if (cboMp3.Checked)
                strFormat = ".mp3";
            else if (cboMp4.Checked)
                strFormat = ".mp4";
            else
                strFormat = ".mp4";

            if (this.cboCustom.Checked)
            {
                this.cboOrg.Checked = false;
                this.txtCustomName.Enabled = true;
                this.lblSaveAs.Text = this.txtCustomName.Text + strFormat;
            }
            else
            {
                this.lblSaveAs.Text = this.lblTitle.Text + strFormat;
                this.txtCustomName.Enabled = false;
            }
        }

        private void txtCustomName_TextChanged(object sender, EventArgs e)
        {
            string strFormat = string.Empty;

            if (cboMp3.Checked)
                strFormat = ".mp3";
            else if (cboMp4.Checked)
                strFormat = ".mp4";
            else
                strFormat = ".mp4";

            this.lblSaveAs.Text = this.txtCustomName.Text + strFormat;

        }

        private void cboOrg_CheckedChanged(object sender, EventArgs e)
        {
            string strFormat = string.Empty;

            if (cboMp3.Checked)
                strFormat = ".mp3";
            else if (cboMp4.Checked)
                strFormat = ".mp4";
            else
                strFormat = ".mp4";

            if (this.cboOrg.Checked)
            {
                this.cboCustom.Checked = false;
                this.lblSaveAs.Text = "video4" + strFormat;
            }
            else
            {
                if (!this.cboCustom.Checked)
                {
                    this.lblSaveAs.Text = this.lblTitle.Text + strFormat;
                }
            }
        }

        private void lblTitle_TextChanged(object sender, EventArgs e)
        {
            if (this.lblTitle.Text != "")
            {

            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            tboLog.Text += "[*] Checking if download link is valid..." + Environment.NewLine;
            //Check so that we have a valid link
            if (this.txtYoutubeLink.Text.IndexOf("watch?v=") > 0)
            {
                tboLog.Text += "[*] Download link is valid, starting download..." + Environment.NewLine;
                thrDownload = new Thread(Download);
                thrDownload.Start();
            }
        }

        private void Download()
        {
            try
            {
                Uri objUri = new Uri(YoutubeDownload.GetYoutubeLink(this.txtYoutubeLink.Text));

                //Get file content
                WebRequest wrRequest = WebRequest.Create(objUri);
                WebResponse wrResponse = wrRequest.GetResponse();
                Stream objStream = wrResponse.GetResponseStream();

                Int64 fileSize = wrResponse.ContentLength;

                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube"))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube");
                }

                FileStream fsStream = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\" + this.lblOrgTitle.Text, FileMode.Create, FileAccess.Write);
                byte[] bteRead = new byte[256];

                int iCount = objStream.Read(bteRead, 0, bteRead.Length);

                while (iCount > 0)
                {
                    fsStream.Write(bteRead, 0, iCount);
                    iCount = objStream.Read(bteRead, 0, bteRead.Length);

                    this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { fsStream.Length, fileSize });
                }

                fsStream.Close();
                objStream.Close();
                wrResponse.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (this.cboMp3.Checked)
                {
                    YoutubeDownload.EncodeFormatFromMp4ToMp3(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\" + this.lblOrgTitle.Text,
                        Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\" + this.lblSaveAs.Text, false);
                }
                else
                {
                    File.Copy(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\" + this.lblOrgTitle.Text,
                        Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\" + this.lblSaveAs.Text, true);
                    File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\video4.mp4");
                }
                if (this.tboLog.InvokeRequired)
                {
                    string strUpdateText = "[*] File completly downloaded, it can be accessed at " + Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\KekTube\\";
                    // It's on a different thread, so use Invoke.
                    SetTextCallback d = new SetTextCallback(updateLog);
                    this.Invoke
                        (d, new object[] { strUpdateText });
                }

            }
        }

        private void updateLog(string strText)
        {
            this.tboLog.Text += strText;
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            iPercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
            this.pgbDownloadFile.Value = iPercentProgress;
        }
    }
}



Am getting the error “URI is empty & URI is Invalid

an I downloaded many projects from your website but I am getting the errors always

am using the Microsoft Visual studio 2010
Posted
Updated 12-Mar-12 7:12am
v2
Comments
[no name] 12-Mar-12 22:08pm    
And the purpose of this code dump would be?

1 solution

If you have questions about the code you're using from an article, post a message in the forum at the bottom of that article. Articles are written by lots of volunteers, not by a small group of people at CP, so we have no idea what article you're refering to nor do we support the code the author wrote. THe author of the article supports their own code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900