C# Download the sound of a youtube video

I can download a video from youtube but I want the sound only. How can I do that?

Code I have for downloading the video (Using VideoLibrary):

        YouTube youtube = YouTube.Default;
        Video vid = youtube.GetVideo(txt_youtubeurl.Text);
        System.IO.File.WriteAllBytes(source + vid.FullName, vid.GetBytes());

Answer

Install the NuGet packages: MediaToolkit and VideoLibrary, it will allow you to do the conversion by file extension.

var source = @"<your destination folder>";
var youtube = YouTube.Default;
var vid = youtube.GetVideo("<video url>");
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());

var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{source + vid.FullName}.mp3" };

using (var engine = new Engine())
{
    engine.GetMetadata(inputFile);

    engine.Convert(inputFile, outputFile);
}

Leave a Reply

Your email address will not be published. Required fields are marked *